Created
October 28, 2022 13:06
-
-
Save mohitsharma93/6050c6b8a099d8b25e953c3b3b003ec6 to your computer and use it in GitHub Desktop.
Bubble sort (JavaScript)sort array to Asc/Desc order
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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