文章目录
快速排序java实现
假设一个数组 int i[] = {6,5,0,7,9,6,1,4,5,12,10,3,8,19};
用快速排序法进行从小到大排序。
原理为寻找一个基准数,一般为第一个数。然后将这个数字取出。从后往前寻找比它小的数,放到前面。这时又有了一个空位。在从前往后寻找比它大的数,放进之前的位置,不断重复。
使用步骤
核心代码:
int start = 0;
int x = i[start];
int end = i.length-1;
while (start<end){
while (start<end&&i[end]>x){
end--;
}
if(start<end){
i[start] = i[end];
start++;
}
while (start<end&&i[start]<x){
start++;
}
if(start<end){
i[end] = i[start];
end--;
}
}
i[start]=x;
运行一次之后:
[3, 5, 0, 5, 4, 1, 6, 6, 9, 12, 10, 7, 8, 19]
运行一次之后,用递归不断调用。
完整实现代码:
int i[] = {6,5,0,7,9,6,1,4,5,12,10,3,8,19};
int start = 0;
int end = i.length-1;
quickSort(i,start,end);
System.out.println(Arrays.toString(i));
}
public static void quickSort(int[] i,int start,int end){
if(start<end){
int middle = middles(i,start,end);
quickSort(i,start,middle-1);
quickSort(i,middle+1,end);
}
}
public static int middles(int[] i,int start,int end){
int x = i[start];
while (start<end){
while (start<end&&i[end]>x){
end--;
}
if(start<end){
i[start] = i[end];
start++;
}
while (start<end&&i[start]<x){
start++;
}
if(start<end){
i[end] = i[start];
end--;
}
}
i[start]=x;
return start;
}
输出
[0, 1, 3, 4, 5, 5, 6, 6, 7, 8, 9, 10, 12, 19]
总结
快速排序在绝大部分时候优于冒泡排序。应当优先使用。