Skip to content

Instantly share code, notes, and snippets.

@jmoyers
Created March 11, 2022 05:53
Show Gist options
  • Save jmoyers/9b341bad1f04ccac2aa012d8fb4388c5 to your computer and use it in GitHub Desktop.
Save jmoyers/9b341bad1f04ccac2aa012d8fb4388c5 to your computer and use it in GitHub Desktop.
// quicksort an array, then map into li elements inside a ul
const ul = document.querySelector('ul');
const li = document.querySelectorAll('li');
const quicksort = (arr) => {
if (arr.length <= 1) return arr;
const pivot = arr[0];
const left = [];
const right = [];
for (let i = 1; i < arr.length; i++) {
if (arr[i] < pivot) {
left.push(arr[i]);
} else {
right.push(arr[i]);
}
}
return quicksort(left).concat(pivot, quicksort(right));
};
const sorted = quicksort(li);
const mapped = sorted.map(el => `<li>${el.textContent}</li>`);
ul.innerHTML = mapped.join('');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment