一、快速排序的思想。
每一次的快排,都是选定一个坐标,把一个数组分隔成两部分。一边是比坐标的数大的数,一边是比坐标的数小的数。
之后把分隔的两个部分在各自选取一个坐标,在分别进行分隔。直到分隔的区间只剩一个数为止。
习惯上把标志位的数放在数组的最后一位上,这样方便进行比较。
快排的一部分过程
二、快速排序的代码。
public class QuickSort {
int [] array = null;
int length = 0;
public QuickSort(int [] array) {
this.array = array;
this.length = array.length;
}
private void Swap (int i,int j){
int temp;
temp = array[i];
array[i] = array[j];
array[j] = temp;
}
private int RandomSubscript(int start,int end){
int index = (int)(Math.random()*(end-start+1)+start);
return index;
}
private int partition(int start,int end){
int small = -1;
int index = RandomSubscript(start, end);
Swap(index , end);
small = start-1;
for(index = start ; index < end ; index++){
if(array[index] < array[end]){
++small;
if(small != index){
Swap(small, index);
}
}
}
++small;
Swap(small,end);
return small;
}
public void printSqrt(){
for(int i = 0 ; i < array.length ; i++){
System.out.print(array[i]+" ");
}
System.out.println();
}
public void quickSqrt(int start,int end){
if(array ==null||array.length<=0){
System.out.println("数组不合法,无法进行排序");
return;
}
if(start<end){
int index = partition(start,end);
if(index > start){
quickSqrt(start,index-1);
}
if(index < end){
quickSqrt(index+1,end);
}
}
return ;
}
}
代码详解:
small是用来卡主比选中的小的数,将比选中的数小的数放在左边,大的数放在右边。small所在的位置是当前最近的比标志数小的数,small之前(包括small)都是比标志数小的数,之后的数都是不确定的。在跳出循环后,small之前(包括)之前的都是比标志位小的,small之后(除了标志位)都是比标志位大的。所以跳出循环后只需要把标志位和samll后面的一个数一交换就可以了。