Skip to content

Instantly share code, notes, and snippets.

@chasingmaxwell
Created July 25, 2020 22:05
Show Gist options
  • Save chasingmaxwell/9678dec4065018f0aa83eccd372af841 to your computer and use it in GitHub Desktop.
Save chasingmaxwell/9678dec4065018f0aa83eccd372af841 to your computer and use it in GitHub Desktop.
Implementation of bubblesort in JavaScript. This might take a while...
// Implementation of bubblesort in JavaScript. This might take a while...
LENGTH = 1e5;
MAX = 2e4;
MIN = 1;
function generateInput(min, max, length) {
const res = [];
while (res.length < length) {
res.push(Math.round(Math.random() * (max - min) + min));
}
return res;
}
function bubbleSort(input) {
const res = [...input];
let leftToSort = input.length;
while (leftToSort > 1) {
for (let n = 0; n < leftToSort; n++) {
let lastModifiedIndex = 0;
for (let i = 1; i < res.length; i++) {
const curr = res[i];
const prev = res[i - 1];
if (curr < prev) {
res[i] = prev;
res[i - 1] = curr;
lastModifiedIndex = i;
}
}
leftToSort = lastModifiedIndex;
console.log("Left to sort:", leftToSort);
}
}
return res;
}
console.log(bubbleSort(generateInput(MIN, MAX, LENGTH)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment