×

Bubble sort algorithm using Javascript

Sorting is a very useful technique in many algorithms and programs. Basically, sorting operations help us to arrange a set of data in a particular manner. Bubble sort is one of the basic and easiest sorting approaches. Let's take an example to discuss sorting.

Before sorting:

304020106070805010090

After sorting:

102030405060708090100

We have numbers in an array, and we want to arrange them in increasing order. To solve this problem, we have to use sorting.

Input-

[30, 40, 20, 10, 60, 70, 80, 50, 100, 90]

Output-

[10, 20, 30, 40, 50, 60, 70, 80, 90, 100]

Explanation- We have sorted the given array in increasing order.

Bubble Sort : - Bubble sort is an easy and slow sorting algorithm. This sorting algorithm is a comparison-based algorithm in which each pair of adjacent elements is compared. After that they are swapped if they are not in order.

Algorithm:-

Step 1: Start

Step 2: All values are taken from the user to build an array.

Step 3: Array is created.

Step 4: A function is called. This function takes the array as input and processes it.

Step 5: We traverse the array n times (n is the size of the array).

Step 6: If we find any element is bigger than its next element, then we swap them.

Step 7: After repeating step 6 in every traversal, we get the sorted array.

Step 8: The returned array will be printed.

Step 9: Stop.

Pseudocode:

Begin bubblesort( list )
			for all elements of list
				if list[ I ] > list[ i+1 ] 
					swap( list[ I ], list[ i+1 ]  )
				end if
			end for
		end bubblesort

Explanation of Algorithm: -

1433273510

Let's try to understand the algorithm with this unsorted array. So, the process of sorting starts with the very first two elements. We compare them to check which one is greater.

1433273510

In this case, 33 is greater than 14, so it is sorted already. Now we go to the next step.

1433273510
1427333510

In this case, 33 is greater than 27, so we swap them. In this way, we traverse all the elements of the array. After the first traversal, we get the last element sorted, and after n times traversal, all elements will be sorted.

Step 1:

1427331035

Step 2:

1427103335

Step 3:

1410273335

Step 4:

1014273335

Code: -

function bubbleSort( arr ){


var i, j;
var len = arr.length;


var isSwapped = false;


for(i =0; i < len; i++){
	
	isSwapped = false;
	
	for(j = 0; j < len; j++){
		if(arr[j] > arr[j + 1]){
		var temp = arr[j]
		arr[j] = arr[j+1];
		arr[j+1] = temp;
		isSwapped = true;
		}
	}
	
	// IF no two elements were swapped by the inner loop, then break
	
	if(!isSwapped){
	break;
	}
}


// Print the array
console.log(arr)
}


// calling the bubbleSort Function
bubbleSort(arr)

Complexity Analysis: -

Time complexity- Bubble sort compares the adjacent elements, hence the number of comparisons

                        = ( n – 1 ) + ( n – 2 ) + ( n – 3 ) + ( n – 4 ) + ( n – 5 ) + ( n – 6 ) + ( n – 7 ) + ……… + 1

                        = n ( n - 1 ) / 2

                        = n^2

Time complexity = O ( n^2 )

Worst case: If we want to sort in ascending order and the array is in descending order, then the worst case occurs. Here time complexity will be O( n^2 ).

Best case: If the array is sorted already.

Space complexity- In this solution, we use constant memory. So, space complexity will be O(1).

Uses of bubble sort: It is a very simple algorithm, so it is often used by beginner-level programmers. It is very helpful to understand the basic concept of sorting. In the polygon filling algorithm, it is used. But as its time complexity is very high so in many algorithms, bubble sort is avoided. Instead of bubble sort, in many cases, merge sort or quick sort is used.


Related Topics

Difference between complete and full binary tree

As we all know that the  binary tree is a tree it contains one or two children at each other node. It contains two children's nodes in the Binary tree. The...

6 minutes read.

What is a Sparse Matrix in Data Structure?

Definition A matrix in which a few non-zero elements are present is called a Sparse matrix. In a Sparse matrix, almost all the matrices are filled with zero (0). A matrix...

5 minutes read.

Preorder Traversal of Binary Trees

In general, Stack, Array, Queue, and other linear data structures only have one way to traverse the data. However, there are numerous ways to traverse through the data in a hierarchical...

3 minutes read.

Recaman’s Sequence

Recamán's succession repeat connection in arithmetic and software engineering. Since its components are obviously connected with the past components, they are as often as possible characterized utilizing recursion. It takes its...

4 minutes read.

Given a Binary Tree, Print the Pre-order Traversal in Recursive

Implementation #include <stdio.h> #include <stdlib.h>   /* Creating a binary tree node that consists of some data along with the pointer to the left and right child.  */ struct __nod {     int record;     struct...

4 minutes read.

Does Overloading Work with Inheritance

This is a question that occasionally comes to many programmers. Who are curious to know more now has a complete explanation and a solution through this tutorial! Inheritance: The functions of...

3 minutes read.

Boruvkas algorithm

This algorithm is used for finding minimum spanning tree from a weighted graph. Like prim’s and kruskal’s algorithm it is also a greedy algorithm. Note:What is the minimum spanning tree?We know...

4 minutes read.

Binary Search Tree vs AVL Tree: Data Structure

Difference Between Binary Search Tree and AVL Tree Binary Search Tree: The binary search tree is a kind of binary tree data structure and it follows the conditions of binary...

3 minutes read.

What is a Tree in Terms of a Graph?

To know the explanation of trees in terms of graphs, we need first to know what trees and graphs are. So let us first learn about trees and graphs. Trees and...

6 minutes read.

Check if a Singly Linked List is Palindrome

Check if a Singly Linked List is Palindrome In this section, we have given a singly linked list, and we need to check whether the given list is a palindrome. Example:           1...

3 minutes read.

Binary search tree traversal in-order pre-order post-order examples

A binary search tree is a type of non-linear tree in which the tree contains at least two nods. It is called binary because of its nature that states bi...

8 minutes read.

Operations of B Tree in C++ Language

B tree tends to be a self-aligning and balancing tree that helps us organise our data and document safely. We know that every data or information in the B tree...

9 minutes read.

Sparse Matrix in Data Structure

Sparse Matrix The sparse matrix is a two-dimensional data object which is made by m rows and n columns, so we can say the number of data values in sparse matrix...

6 minutes read.

Sort the linked list of 0s, 1s and 2s

Sort the linked list of 0s, 1s and 2s In this, we are given a linked list of 0s, 1s, and 2s, and we need to sort it. Examples: Input: 1  ->  1 ...

2 minutes read.

Data Structures Tutorial

The data structure is a way of storing and organizing data in a computer system. So that we can use the data quickly, which means the information is stored and...

7 minutes read.

Semi-Structured data

In this article, we will discuss the semi-structured data. Data can be defined as the distinct piece of information that is gathered and translated for some purpose. It can be...

5 minutes read.

Serialize and Deserialize Binary Trees

In order to save a tree in a file that can later be restored, serialisation is used. The tree's structure must be preserved. Deserialization involves reading a tree from a...

4 minutes read.

Difference between B-tree and Binary Tree

What is B-TREE? The nodes of B-tree are sorted during in-order traversal, and it is called self-balancing tree. A node in a B-tree can have more than two offspring, in contrast...

3 minutes read.

Finding Rank in a Binary Search Tree

Implementation // writing a C++ program to find out the rank and element in the program.  #include <bits/stdc++.h> using namespace std; struct __nod { int record; __nod *Lft, *Rt; int LftSize; }; __nod* new__nod(int record) { __nod *temp = new __nod; temp->record...

6 minutes read.

Binary Search Tree

Binary Search Tree: A binary search tree is a type of tree in which every node is organized in the sorted order. It is also called an ordered binary tree. Properties...

4 minutes read.