Bubble Sort in Javascript
Comparing each with the neighbor and swapping if first is greater than the next
Time Complexity
Best: Ω(n^2)
Average: θ(n^2)
Worst: O(n^2)
function bubbleSort(arr){
console.log("Input Array");
console.log(arr);
let i = 0
let temp;
let notSorted;
do {
notSorted = false;
for (let j = 0; j < arr.length-i; j++) {
if (arr[j] > arr[j+1]) {
notSorted = true;
temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp;
console.log(arr[j],"swapped with",arr[j+1])
console.log(arr);
} else {
console.log("SKIP");
}
console.log(j, arr.length-i);
}
i++;
} while (notSorted)
console.log("Sorted using Bubble Sort");
return arr;
}
// console.log(bubbleSort([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20])); // uncomment to run and see how efficient this algorithm is when array is sorted
console.log(bubbleSort([5,8,18,4,19,13,1,3,2,20,17,15,16,9,10,11,14,12,6,7]));
Recursive Bubble Sort in Javascript
Bubble Sort can be carried out recursively as follows:
const recursiveBubbleSort = function (a, p = a.length-1) {
if (p < 1) {
return a;
}
for (let i = 0; i < p; i++) {
if (a[i] > a[i+1]) {
[a[i], a[i+1]] = [a[i+1], a[i]];
}
}
return recursiveBubbleSort(a, p-1);
}
console.log(recursiveBubbleSort([2,1,4,7,3,9,5,6,8]));
You can run the code here: https://repl.it/@VinitKhandelwal/bubble-sort-recursive-javascript
Comments
Post a Comment