今天開始學Java 排序算法之快速排序

思路:先選一個“標尺”, 用它把整個隊列過一遍篩子, 以保證:其左邊的元素都不大於它,其右邊的元素都不小於它。排序問題就被分割爲兩個子區間。 再分別對子區間排序就可以了。

不明白的話看代碼:

public class InsertSort {
public static int sort(int[] a,int start,int end){
int base = a[end];
while(start <end){
//IF語句運行完畢後,接着運行下面的語句。而While中的執行語句運行完畢後,
//還要進行繼續判斷條件是否符合循環條件,根據判斷的條件,返回執行語句或繼續運行下面的程序。
if(start <end && a[start] <= base){
start++;
}
if(start <end && a[start] >= base){
int tmp = a[start];
a[start] =a[end];
a[end] = tmp;
end--;

}
if(start<end && a[end] >= base){
end--;
}
if(start <end&& a[end] <= base){
int tmp = a[start];
a[start] =a[end];
a[end] = tmp;
start++;
}

}
return end;

}

public static void partitionsort(int[] a,int start,int end){
if(start>=end){return;}
else{
int i = sort(a,start,end);
partitionsort(a,start,i-1);
partitionsort(a,i+1,end);


}
}


public static void main(String[] args) {
// TODO Auto-generated method stub
int[] a = {4};
       //InsertSort sort1 = new InsertSort();
       int start = 0;
       int end = 0;
       partitionsort(a,start,end);
       for (int i =0;i<a.length;i++){
       System.out.print(a[i]+" ");
       } 
       }

}

第一輪循環後,base找到屬於自己的位置了就不動,然後將其左右兩邊的序列再按照這種方法遞歸一下。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章