您的位置:首页 > 其它

排序算法之快排

2016-05-28 18:29 387 查看

快速排序代码:

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) {
// TODO Auto-generated catch block
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]+" ");
}
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  快排