Skip to content

Instantly share code, notes, and snippets.

@mohitsharma93
Created October 28, 2022 13:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mohitsharma93/6050c6b8a099d8b25e953c3b3b003ec6 to your computer and use it in GitHub Desktop.
Save mohitsharma93/6050c6b8a099d8b25e953c3b3b003ec6 to your computer and use it in GitHub Desktop.
Bubble sort (JavaScript)sort array to Asc/Desc order
const arr = [-2, 45, 0, 11, -9];
/*
* Bubble sort is a sorting algorithm that compares two adjacent elements and swaps them until they are in the intended order.
*/
function bubbleSort(arr) {
// loop to access each array element
for (let i = 0; i < arr.length; i++) {
// keep track of swapping
let swap = false;
// loop to compare two elements
for (let j = 0; j < (arr.length - i); j++ ) {
// compare two array elements
// change > to < to sort in descending order
if (arr[j] > arr[j + 1]) {
// swap if elements are not in intended order.
const oldJ = arr[j];
arr[j] = arr[j+1];
arr[j + 1] = oldJ;
swap = true;
}
}
// no swapping means the array is already sorted so no need of further comparison.
if (!swap) break;
}
return arr;
}
console.log(bubbleSort(arr))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment