Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save whitershade/76de90c94ad109d245597498b4945ebd to your computer and use it in GitHub Desktop.
Save whitershade/76de90c94ad109d245597498b4945ebd to your computer and use it in GitHub Desktop.
sort
const array = [2, 4, 6, 10, 7, 3, 5];
const qsort = array => {
if (array.length < 2) return array;
const pivot = array[Math.round(array.length / 2)];
const less = array.filter(i => i < pivot);
const greater = array.filter(i => i > pivot);
return [...qsort(less), pivot, ...qsort(greater)];
};
const bubbleSort = array => {
const sorted = [...array];
for (let i = 1; i < sorted.length; i += 1) {
for (let j = 0; j < sorted.length - 1; j += 1) {
if (sorted[j] > sorted[j + 1]) {
[sorted[j], sorted[j + 1]] = [sorted[j + 1], sorted[j]];
}
}
}
return sorted;
};
const selectionSort = array => {
const sorted = [...array];
for (let i = 0; i < sorted.length - 1; i += 1) {
let minIndex = i;
for (let j = i; j < sorted.length; j += 1) {
if (sorted[j] < sorted[minIndex]) {
minIndex = j;
}
}
if (minIndex !== i) {
[sorted[i], sorted[minIndex]] = [sorted[minIndex], sorted[i]];
}
}
return sorted;
}
console.log(qsort(array));
console.log(bubbleSort(array));
console.log(selectionSort(array));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment