Skip to content

Instantly share code, notes, and snippets.

@soyart
Created September 19, 2021 17:25
Show Gist options
  • Select an option

  • Save soyart/bd6afba3145fcbd4c7d150f7bff1229a to your computer and use it in GitHub Desktop.

Select an option

Save soyart/bd6afba3145fcbd4c7d150f7bff1229a to your computer and use it in GitHub Desktop.
Bubble sort in JS
const array = [2, 100, 4, 5, 7, 21, 13];
const bubbleSortInPlace0 = (arr) => {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j+1]) {
[arr[j], arr[j+1]] = [arr[j+1], arr[j]]
};
};
};
return arr;
}
const bubbleSortInPlace1 = (arr) => {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (arr[j] > arr[j+1]) {
let temp = arr[j];
arr[j] = arr[j+1];
arr[j+1] = temp
};
};
};
return arr;
}
const bubbleSortNewArary = (arr) => {
const out = arr.slice();
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
const out = arr.slice();
if (out[j] > out[j+1]) {
[out[j], out[j+1]] = [out[j+1], out[j]]
};
};
};
return out;
};
console.log(bubbleSortInPlace0(array));
console.log(bubbleSortInPlace1(array));
console.log(bubbleSortNewArary(array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment