Last active
November 28, 2021 17:29
-
-
Save itsAnanth/d339b5acd0ca5846585e0f9003133667 to your computer and use it in GitHub Desktop.
Implementation of bubble sort in javascript
This file contains hidden or 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
// bubble sort in javascript | |
Array.prototype.bubbleSort = function(callback = (a, b) => a > b) { | |
const array = this; | |
for (let i = 0; i < array.length; i++) { | |
let swaps = 0; | |
for (let j = 0; j < array.length - i - 1; j++) { | |
if (callback(array[j], array[j + 1])) { | |
let temp = array[j]; | |
array[j] = array[j + 1]; | |
array[j + 1] = temp; | |
swaps ++; | |
} | |
} | |
if (swaps === 0) break; | |
} | |
} | |
const array = [21, 1, 2, 6, 10, 12, 10, 21, 5, 9, 0]; | |
// a > b for sorting in ascending order | |
// a < b for descending | |
array.bubbleSort((a, b) => a > b); | |
console.log(array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment