Skip to content

Instantly share code, notes, and snippets.

@zhongfox zhongfox/quick_sort

Last active Aug 29, 2015
Embed
What would you like to do?
javascript quick sort
var rawNumbers = [4,4,3,1,8,5,13,9,2,7,18,10,4];
function qsort(numbers, startIndex, endIndex) {
var first = startIndex,
last = endIndex,
key = numbers[first];
if(first >= last) {
return;
}
while(first < last) {
while(first < last) {
if(numbers[last] < key) { //相等的也不移动, 或者一边移动, 不能2个都移动相等的
numbers[first] = numbers[last];
break;
}
last--;
}
while(first < last) {
if(numbers[first] > key) { // 相等的也不移动, 或者一边移动, 不能2个都移动相等的
numbers[last] = numbers[first];
break;
}
first++;
}
}
numbers[first] = key;
qsort(numbers, startIndex, first - 1);
qsort(numbers, first + 1, endIndex); //first last 此时first last应该相等
}
qsort(rawNumbers, 0, rawNumbers.length);
console.log(rawNumbers);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.