×

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

Red-black Tree in Data Structures?

A type of binary tree which is known as the Red-Black tree, is a specialized and unique tree. What is the urgency or, to be more precise, the necessity of...

10 minutes read.

Given a Perfect Binary Tree, Reverse Alternate Levels

Implementation //writing a program in C++ language to see how to approach it. #include <bits/stdc++.h> using namespace std; // creating a tree node. struct Nod { char ky; struct Nod *Lft, *Rt; }; // creating a new utility function...

9 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 Implementation Using Arrays

Implementation Converting a binary tree into a list of arrays is one interesting problem. Let us see that in depth. In this section, we will see the implementation of the binary Trees...

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.

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.

Right side view of binary tree

The right view of the binary tree is generally known to be that side viewed from the right direction of the point of view. To be more precise, the right-side...

8 minutes read.

Digital Search Tree in Data Structures

What is a digital search Tree in Data Structures? The Digital search tree is known for its application and diversity in the way it has impacted our world in the field...

3 minutes read.

Traversal of binary tree

Traversal of binary tree: A node is visited only once in the traversal of the binary tree. There are three main types of traversal methods in the binary tree. In-order traversalPre-order...

3 minutes read.

Cocktail Sort

C Program executes cocktail sort. Combo sort is a somewhat straightforward arranging calculation initially planned by Wlodzimierz Dobosiewicz and Artur Borowy in 1980, later rediscovered by Stephen Lacey and Richard Box...

5 minutes read.

Detect and Remove Loop in a Linked List

Create a function called detectAndRemovetheLoop() that verifies whether a given Linked List has a loop, eliminates the loop if it does, and returns true if it does. It returns false...

6 minutes read.

Given Two Binary Trees, Check if it is Symmetric

Implementation // creating a C++ program that will help us check whether the two given trees are mirror images of each other.  #include<bits/stdc++.h> using namespace std; /* A given binary tree has a data...

5 minutes read.

Deletion Operation from A B Tree

This article will show the deletion operation through the b tree in C++ programming language. Implementation #include <iostream> using namespace std; class B_TreeNod {   int *kys;   int m;   BTreeNod **C;   int j;   bool leaf;  ...

5 minutes read.

Introduction to 2D-Arrays

Two Dimensional Array Technical Definitions An array of arrays is a common definition for a two-dimensional array. A matrix is another name for a two-dimensional array. A matrix looks like a table...

3 minutes read.

Insertion in B+ Tree

We will learn how to insert a node in the B+ tree and what are the different properties we are going to follow. Except for the root node, every node should...

5 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.

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.

Merge two sorted linked lists

Merge two sorted linked lists In this article, we are going to learn how to merge two linked lists. Here we have given two linked lists that are sorted in increasing...

7 minutes read.

Buffer overflow attack with examples

You have undoubtedly faced the term buffer overflow in your programming journey. Many times it occurs when we try to run a piece of code with user input, but it...

4 minutes read.

Invert binary tree

Invert binary tree is a mirror image of a tree. It is pretty much the same compared to the only difference: its left and right children are swapped with the...

4 minutes read.