Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Bubble sort
function bubbleSort(array) {
let res = [...array];
let status = new Array(res.length - 2).fill(false);
while (!status.every(e => e === true)) {
for (let i = 0; i < res.length - 1; i++) {
if (res[i] > res[i + 1]) {
// swap values
let temp = res[i];
res[i] = res[i + 1];
res[i + 1] = temp;
status[i] = false;
} else {
status[i] = true;
}
}
}
return res;
}
function logTimeProcess(name, fn) {
const t0 = performance.now();
console.log(fn()); // <---- The function you're measuring time for
const t1 = performance.now();
return `this function ${name} takes ${t1 - t0} milliseconds.`;
}
const arr = [1, 2, 4, 3, 2, 9, 3, 5, 6789, 2, 11, 1, 0];
console.log(logTimeProcess("native sort", () => arr.sort((a, b) => a - b)));
console.log(logTimeProcess("personnal sort", () => bubbleSort(arr)));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment