Sunday, December 21, 2014

快速排序实现

注:此快速排序取第一个值为pivot,把小于pivot的数放到左边,大于的放到右边

public class QuickSort {

public static void main(String[] args) {
int arr[]=new int[50];
for(int i=0;i<arr.length;i++)
arr[i]=(int)(Math.random()*100);
//int arr[]={ 49, 42, 36};
//..int arr[]={8,7,8,8};
//for(int i=0;i<arr.length;i++){
// System.out.print(arr[i]+" ");
//}
System.out.println();
quickSort(arr,0,arr.length-1);
for(int i=0;i<arr.length;i++){
System.out.print(arr[i]+", ");
}

}
public static void quickSort(int[] array,int start,int end){
int temp;

if(start>=end){return;}//大于号非常重要,如果没有,会导致index越界
if(start==end-1){        //base condition,两个数的比较,必须有
if(array[start]>array[end]){
temp=array[start];
array[start]=array[end];
array[end]=temp;
return;
}else
return;
}
int pivot=array[start];

int i=start+1;
int j=end;
while(i<j){
while(array[i]<=pivot&i!=end){//注意=很重要,否则无限循环
i++;
if(i==end&array[i]<pivot){
//非常重要,这是极端情况,考虑到如果pivot取的是最大值的情况
array[start]=array[end];
array[end]=pivot;
quickSort(array, start, i-1 );
return;
}
}
while(array[j]>=pivot&j!=start){
j--;
}
temp=array[j];
//i,j交换后需要交换回来,例如8(start),0,3,16(j),5(i),18,12,9    i=4,j=3
array[j]=array[i];
array[i]=temp;

}
temp=array[j];
array[start]=array[i];
array[j]=pivot;
array[i]=temp;
//System.out.println("j="+j+" start="+start);
quickSort(array, start, j-1 );
quickSort(array,j+1,end);

}
}
0, 1, 1, 2, 2, 3, 4, 15, 16, 17, 19, 22, 25, 27, 30, 36, 40, 41, 46, 46, 51, 53, 55, 55, 58, 59, 63, 64, 64, 65, 66, 66, 72, 73, 73, 74, 77, 78, 78, 78, 81, 81, 81, 86, 91, 92, 95, 99, 99, 99, 

No comments:

Post a Comment