fix(Javascript): bubble sort (#647)
parent
bf2b27489d
commit
b5d44d3bd3
|
@ -1,21 +1,52 @@
|
||||||
// Bubble Sorting JavaScript Version
|
// Bubble Sorting JavaScript Version
|
||||||
|
|
||||||
function bubbleSort(arr) {
|
// Bubble sort is a sorting algorithm in which
|
||||||
// Copy the contents of the input array and store them as a separate variable
|
// the largest element is moved or bubbled up
|
||||||
const sorted = [...arr];
|
// to the end of the array in every iteration
|
||||||
|
|
||||||
// Loop through the copied array
|
function bubbleSort(arr) {
|
||||||
for (let i = 0; i < sorted.length; i++) {
|
// a variable to hold temporary value
|
||||||
// Checks if an item in the array is
|
let temp;
|
||||||
// greater than the item next to it (index + 1)
|
|
||||||
if (sorted[i] > sorted[i + 1]) {
|
// a boolean flag to skip iterations if
|
||||||
// If yes, swap them
|
// the array gets sorted mid way, happens
|
||||||
sorted.splice(i, 2, sorted[i + 1], sorted[i]);
|
// in case of large almost sorted array
|
||||||
|
// as shown in the second example call
|
||||||
|
// to bubble sort.
|
||||||
|
let isNoSwap;
|
||||||
|
|
||||||
|
// the outer loop starts from one end
|
||||||
|
// and we decrease the no. of iterations we have
|
||||||
|
// to make as after every iteration, the array
|
||||||
|
// starts getting sorted from the top end.
|
||||||
|
for (let i = arr.length - 1; i > 0; i--) {
|
||||||
|
isNoSwap = true;
|
||||||
|
|
||||||
|
// we start the inner loop from 0 to i
|
||||||
|
// as after ith index the elements are sorted
|
||||||
|
for (let j = 0; j < i; j++) {
|
||||||
|
if (arr[j] > arr[j + 1]) {
|
||||||
|
temp = arr[j];
|
||||||
|
arr[j] = arr[j + 1];
|
||||||
|
arr[j + 1] = temp;
|
||||||
|
isNoSwap = false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// if there hasn't been a swap
|
||||||
|
// in the previous iteration
|
||||||
|
// the array is sorted
|
||||||
|
// so no point going on and on
|
||||||
|
// skip the iterations and get out of loop.
|
||||||
|
if (isNoSwap) {
|
||||||
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Finally return the sorted array
|
return arr;
|
||||||
return sorted;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
// Log to the console and have fun
|
// Log to the console and have fun
|
||||||
console.log(bubbleSort([23, 34, 25, 12, 54, 11]));
|
console.log(bubbleSort([23, 34, 25, 12, 54, 11]));
|
||||||
|
|
||||||
|
// example of almost sorted array
|
||||||
|
console.log(bubbleSort([8, 1, 2, 3, 4, 5, 6, 7]));
|
||||||
|
|
Loading…
Reference in New Issue