Skip to content

Instantly share code, notes, and snippets.

@Ikhan
Created May 21, 2019 14:58
Show Gist options
  • Save Ikhan/db0b5204a9b9330a7de970b223081684 to your computer and use it in GitHub Desktop.
Save Ikhan/db0b5204a9b9330a7de970b223081684 to your computer and use it in GitHub Desktop.
//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])
@Ikhan
Copy link
Author

Ikhan commented May 21, 2019

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;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment