Skip to content

Instantly share code, notes, and snippets.

@zhongyangxun
Created January 15, 2021 07:34
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhongyangxun/4ba6c61e99643295436970aa00f1282c to your computer and use it in GitHub Desktop.
Save zhongyangxun/4ba6c61e99643295436970aa00f1282c to your computer and use it in GitHub Desktop.
Quick sort algorithm based on JavaScript.
function quickSort(list) {
return sortCore(list, 0, list.length - 1);
}
function sortCore(list, first, last) {
if (last <= first) {
return list;
}
const povitIndex = partition1(list, first, last);
// const povitIndex = partition2(list, first, last);
sortCore(list, povitIndex + 1, last);
sortCore(list, first, povitIndex - 1);
return list;
}
function partition1(list, first, last) {
if (last <= first) {
return;
}
const povit = list[first];
let low = first + 1;
let high = last;
while(high > low) {
while(high > low && list[high] > povit) {
high--;
}
while(high > low && list[low] <= povit) {
low++;
}
if (high > low) {
swap(list, high, low);
}
}
while(high > 0 && list[high] > povit) {
high--;
}
if (high > 0) {
swap(list, first, high);
return high;
}
return first;
}
function partition2(list, first, last) {
const povit = list[last];
let small = first - 1;
for (let i = first; i < last; i++) {
if (list[i] <= povit) {
small++;
if (small !== i) {
swap(list, small, i);
}
}
}
const povitIndex = small + 1;
swap(list, povitIndex, last);
return povitIndex;
}
function swap(list, a, b) {
const temp = list[a];
list[a] = list[b];
list[b] = temp;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment