快速排序代码:
public class QuickSort {
public int partation(int [] array ,int length,int start,int end) {
if (array ==null||length<=0 ||start<=0 ||end>=length){
try {
throw new Exception();
} catch (Exception e) {
e.printStackTrace();
}
}
int index=(new Random().nextInt(end-start))+start;
swap(array ,index,end);
int small=start-1 ;
for (index=start;index<end;index++){
if (array [index]<array [end]){
++small;
swap(array ,small,index);
}
}
++small;
swap(array ,small,end);
return small;
}
public void swap(int [] array ,int a,int b){
int n=array [a];
array [a]=array [b];
array [b]=n;
}
public void quickSort(int [] array ,int length,int start,int end){
if (start==end){
return ;
}
int index=partation(array , length, start, end);
if (index>start){
quickSort(array , length, start, index-1 );
}
if (index<end){
quickSort(array , length,index+1 , end);
}
}
public static void main(String[] args){
int [] num={4 ,3 ,5 ,6 ,2 ,7 ,1 };
QuickSort s=new QuickSort();
s.quickSort(num, num.length, 0 , num.length-1 );
for (int i=0 ;i<num.length;i++){
System.out.print(num[i]+" " );
}
}
}