Bubble Sort algorithm using
JavaScript
Bubble sort algorithm is an algorithm
that sorts an array by comparing two
adjacent elements and swapping them
if they are not in the intended order.
Here order can be anything like
increasing or decreasing.
How Bubble-sort works?
We have an unsorted array arr = [ 1, 4,
2, 5, -2, 3 ], and the task is to sort the
array using bubble sort in ascending
order.
Bubble sort compares the element from
index 0 and if the 0th index value is
greater than 1st index value, then the
values get swapped and if the 0th
index value is less than the 1st index
value, then nothing happens.
Next, the 1st index value compares to
the 2nd index value, and then the 2nd
index value compares to the 3rd index
value, and so on…
Let’s see with an example.
Here, each step is briefly
illustrated:
After each iteration, the greatest value of the array becomes the last
index value of the array. In each iteration, the comparison happens
till the last unsorted element.
After all the iteration and
comparisons of elements, we get a
sorted array.
The syntax for solution :-
BubbleSort(array){
for i -> 0 to arrayLength
isSwapped <- false
for j -> 0 to (arrayLength - i - 1)
if arr[j] > arr[j + 1]
swap(arr[j], arr[j + 1])
isSwapped -> true
}
Code :-
function bubbleSort(array) {
const arrayLength = array.length;
let isSwapped;
for (let i = 0; i < arrayLength; i++) {
isSwapped = false;
for (let j = 0; j < arrayLength - i - 1;
j++) {
if (array[j] > array[j + 1]) {
// Swap elements
[array[j], array[j + 1]] = [array[j +
1], array[j]];
isSwapped = true;
}
}
// If no two elements were swapped
in the inner loop, array is sorted
if (!isSwapped)
break;
}
return array;
}
// Test the function
const sortedArray = bubbleSort([45, 23,
3, 5346, 5, 356, 243, 35]);
console.log("Sorted Array:");
console.log(sortedArray);
Output: Sorted Array
[3, 5, 23, 35, 45, 243, 356, 5346]
Complexities
Worst Case and Average case time complexity
If the array is in reverse order then this condition
is the worst case and Its time complexity is
O(n2).
Best case time complexity
If the array is already sorted then it is the best-
case scenario and its time complexity is O(n)
Auxiliary Space: O(1)