左边的都小于key,右边的都大于等于key
java实现:
import java.util.*;
public class Quick_Sort {
public static void main(String[] args) {
List<Integer> list = new ArrayList<>();
Scanner in = new Scanner(System.in);
while(in.hasNext()) {
String s = in.nextLine().replace(" ", ""); //只针对0到9,范围以外需要修改输入判断
int len = s.length();
for (int i = 0; i < len; i++) { //去除无用空格,只针对0到9,范围以外需要修改输入判断
list.add(Integer.parseInt(String.valueOf(s.charAt(i))));
}
q_rec(list,0,list.size()-1); //调用递归
System.out.println(list);
}
}
//排序方法,保证前面数小于key对应的数,后面数大于等于key对应的数
private static int q_sort(List<Integer> list, int from, int to) {
int start = from;
int end = to;
int key = list.get(start);
while (start < end) {
while (end > start && list.get(end) >= key) { //从后往前找到第一个小于key对应的数
end--;
}
if (end > start) { //找到小于key的则覆盖
list.set(start, list.get(end));
start++;
} else {
break;
}
while (start < end && list.get(start) < key) { ////从前往后找到第一个大于等于key对应的数
start++;
}
if (start < end) { //找到大于等于key的则覆盖
list.set(end, list.get(start));
end--;
} else {
break;
}
}
list.set(start, key);
return start;
}
//递归调用排序方法
private static void q_rec(List<Integer> list ,int from,int to){
if(from < to){
int flag = q_sort(list, from, to);
q_rec(list, from, flag-1);
q_rec(list, flag+1, to);
}
}
}
js实现:
function quick_swap(arr,start,end){
var key = arr[start];
var left = start;
var right = end;
while(left < right){
while(left < right && arr[right] > key){
right--;
}
if(left < right){
arr[left] = arr[right];
left++;
}
while(left < right && arr[left] <= key){
left++;
}
if(left < right) {
arr[right] = arr[left];
right--;
}
}
arr[left] = key;
return left;
}
function quick_rec(arr,start,end){
if(start < end){
var flag = quick_swap(arr,start,end);
quick_rec(arr,start,flag-1);
quick_rec(arr,flag+1,end);
}
}
function quick_sort(array){
var arr = array.concat();
var len = arr.length;
quick_rec(arr,0,len-1);
alert(arr);
}