Created
July 25, 2020 22:05
-
-
Save chasingmaxwell/9678dec4065018f0aa83eccd372af841 to your computer and use it in GitHub Desktop.
Implementation of bubblesort in JavaScript. This might take a while...
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
// 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