Skip to content

Instantly share code, notes, and snippets.

@jayantasamaddar
Created May 23, 2022 13:25
Show Gist options
  • Save jayantasamaddar/b4818ab28e280d214560571c122086b5 to your computer and use it in GitHub Desktop.
Save jayantasamaddar/b4818ab28e280d214560571c122086b5 to your computer and use it in GitHub Desktop.
Implement a Bubble Sort Algorithm
/* Using C Style for-Loop */
const bubbleSort = array => {
const arr = array.slice();
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
}
return arr;
};
/* Using while-loop */
const bubbleSort2 = array => {
const arr = array.slice();
let counter = arr.length;
while (counter > 0) {
for (let i = 0; i < arr.length - 1; i++) {
if (arr[i] > arr[i + 1]) swap(arr, i, i + 1);
}
counter--;
}
return arr;
};
/* Using recursive Function */
const bubbleSort3 = array => {
const arr = array.slice();
const recursiveSort = (arr, indx) => {
let i = indx;
if (i === arr.length - 1) return arr;
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j + 1]) {
swap(arr, j, j + 1);
}
}
i++;
return recursiveSort(arr, i);
};
return recursiveSort(arr, 0);
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment