Skip to content

Instantly share code, notes, and snippets.

@likev
Created September 17, 2022 03:06
Show Gist options
  • Save likev/4d734ee448e7f34d36a7a2f6b67f27c2 to your computer and use it in GitHub Desktop.
Save likev/4d734ee448e7f34d36a7a2f6b67f27c2 to your computer and use it in GitHub Desktop.
quick sort using js demo with test
var count = 0;
function quicksort(arr) {
let length = arr.length,
pos = Math.floor(Math.random() * length); //pick a random index position
if (length <= 1) return arr;
//if (++count > 10) return console.log('error');
/*
console.log({
arr,
pos,
posv: arr[pos]
})
*/
let left = arr.filter((v) => v < arr[pos]),
center = arr.filter((v) => v === arr[pos]), //center is all equal already
right = arr.filter((v) => v > arr[pos]);
return [...quicksort(left), ...center, ...quicksort(right)]
}
console.log(quicksort([]))
console.log(quicksort([3]))
console.log(quicksort([7, 5]))
console.log(quicksort([4, 7, 5]))
console.log(quicksort([4, 7, 5, 6]))
var test = n => { //test n times
let error = false;
for (let i = 0; i < n && !error; i++) {
let length = Math.floor(Math.random() * n);
let arr = [];
for (let j = 0; j < length; j++) {
arr.push(Math.floor(Math.random() * n))
}
//console.log(arr)
const arr_sort = quicksort(arr);
//check whether arr_sort is sorted
for (let j = 1; j < arr_sort.length; j++) {
if (arr_sort[j] < arr_sort[j - 1]) {
console.log('error');
error = true;
break;
}
}
//console.log(arr_sort)
}
if (!error) console.log('all pass');
}
test(1E2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment