Created
May 21, 2019 14:58
-
-
Save Ikhan/db0b5204a9b9330a7de970b223081684 to your computer and use it in GitHub Desktop.
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
//naive solution | |
function bubbleSort(arr) { | |
for (let i=0; i< arr.length; i++) { | |
for (let j=0; j< arr.length; j++) { | |
console.log(arr, arr[j], arr[j+1]); | |
if (arr[j] > arr[j+1]) { | |
//swap | |
let temp = arr[j]; | |
arr[j] = arr[j+1]; | |
arr[j+1] = temp; | |
} | |
} | |
} | |
return arr; | |
} | |
//optimized solution | |
function bubbleSort(arr) { | |
for (let i=arr.length; i > 0; i--) { | |
for (let j=0; j < i-1; j++) { | |
console.log(arr, arr[j], arr[j+1]); | |
if (arr[j] > arr[j+1]) { | |
//swap | |
let temp = arr[j]; | |
arr[j] = arr[j+1]; | |
arr[j+1] = temp; | |
} | |
} | |
} | |
return arr; | |
} | |
bubbleSort([84,10,2,4,8,1,12]) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
more nice es6 version
function bubbleSort(arr) {
const swap = (arr, idx1, idx2) => {
[arr[idx1], arr[idx2]] = [arr[idx2], arr[idx3]];
}
for (let i=arr.length; i > 0; i--) {
for (let j=0; j < i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr, j, j+1)
}
}
}
return arr
;}