×

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

Insertion sort

Insertion sort is a simple sorting technique. It is best suited for small data sets, but it does not suitable for large data sets. In this technique, we pick an...

4 minutes read.

Difference between Stack and Queue

In this article, we will learn about the major differences between Stack and Queue data structures. What is a stack? Stack – A stack is an abstract data structure defined as the...

3 minutes read.

Shell Sort

Shell Sort: Shell sort is a sorting algorithm. It is an extended version of the insertion sort. In this sorting, we compare the elements that are distant apart rather than the...

5 minutes read.

B Tree vs B + Tree: Data Structure

Difference Between B Tree and B+ Tree What is B Tree? B-Tree is a self-balancing or special type of m-way tree. B-Trees are used mainly in disc access. If we want...

3 minutes read.

Inorder Successor in Binary Trees

The next node in the Inorder traversal of a binary tree is known as Inorder successor of that particular node. In a Binary Search Tree, the definition of Inorder successor can...

9 minutes read.

Queue Data Structure

Queue in DS: The queue is a non-primitive and linear data structure. It works on the principle of FIFO (First In First Out). That is, the element that is added...

4 minutes read.

Binary Tree in Data Structures

What is a Binary Tree in Data Structures? The term binary itself means bi, which implies two of anything. So very clearly, we know we present the trees in the form...

6 minutes read.

Operations on Queue in Data Structures

A queue is a linear structure where operations are done in a specific sequence. Queues are abstract data structures that are comparable to Stacks. A queue, unlike a stack, is...

8 minutes read.

Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size This article will explain how to reverse a linked list in groups of given size. Here we have given a linked list...

2 minutes read.

Number of visible boxes putting one inside another

You have given one array, which consists of values which represent the sizes of different boxes. We can put one box inside another if the size of the outside box...

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.

Optimal binary search tree using dynamic programming

Implementation // We are creating a presentation where we will present a recursive method of the optimal binary search tree problem.  #include <bits/stdc++.h> using namespace std; //creating a utility function that will help us...

9 minutes read.

B+ Tree in Data Structure

A B-Tree extension called B+ Tree, which enables effective search, insertion, and deletion operations. Both Records and keys can be stored in internal and leaf nodes in a B tree. Contrarily,...

4 minutes read.

Convert Binary Tree into a Threaded Binary Tree

Implementation /*Writing a C++ program that will help us change the binary tree into a threaded binary tree and help us transform. */ #include <bits/stdc++.h> using namespace std; /*Creating the structure of a node...

11 minutes read.

Convert a Binary Tree into a Binary Search Tree

Implementation #include <stdio.h>   #include <stdlib.h>       //creating a node of the binary tree.  struct __nod{       int record;       struct __nod *Lft;       struct __nod *Rt;   };       // presenting the root of the binary tree.   struct...

5 minutes read.

What Is Dfs Algorithm in Data Structures

DFS stands for Depth First Search. Generally, it is a repetitive or decidable type of algorithm which is basically used in identifying all the vertices or nodes of a graph...

5 minutes read.

Compare Balanced Binary Tree and Complete Binary Tree

Complete and balanced binary trees are important and general topics in the concept – Tree data structure. Before discussing the complete and balanced binary tree, we need to have an...

8 minutes read.

Binary Tree to Doubly Linked List

Binary Tree to Doubly Linked List This article will explain how to convert the given binary tree into a Doubly Linked List. The left and right pointers in tree nodes are...

2 minutes read.

Find Bridges in a Graph

You have been given a graph. You have to find out the bridges in that graph. Graph may be connected or disconnected. You have to print vertices of particular edge...

4 minutes read.

Create a binary search tree

Implementation In this section of the article, we will see the usage and mechanism of how we will create a given binary tree. Let's observe these in more depth and then...

7 minutes read.