快速排序

 

 

 

 

 

 

 

 

package com.JBUtils.Arithmetic;

 

/*

  快速排序大體說來:

    1)就是從一堆數選出一個數,將小與該數的數放在其左邊,把大於該數的數排在其右邊。(子問題)

    2)然後就是重複1步驟,直到該堆數只有一個數(分冶)。

*/

public class JBQuikSort {
/**
* 分解子問題
* 這裏用的分冶的思想 直接就是分爲左右兩邊 直到分到只有一個數位置
* @param array
*/
public void sort(Integer []array,int start,int end){
if(start<end){
int pos=sort0(array,start,end);//pos的位置 已經是正確的位置 無需在處理
sort(array,start,pos-1);
sort(array,pos+1,end);
}
}
public int findMiddleData(Integer []array,int start,int end){

int pos=sort0(array,start,end);//pos的位置 已經是正確的位置 無需在處理
if(pos==((start+end)/2)){
return pos;
}else if(pos>((start+end)/2)){
return findMiddleData(array,pos-1,end);
}else {
return findMiddleData(array,pos+1,end);
}
}
/**
* 子問題求解 假設極端情況 就只剩下三個數 是如何操作的?
* @param array
* @param start
* @param end
*/
private int sort0(Integer []array,int start,int end){
int standard=array[start];
while(start<end){
while(start<end&&array[end]>standard){
end--;
}
if(start<end){//說明右邊找到一個比標準大的數,那麼就往左邊的坑填
array[start]=array[end];
start++;
}
while(start<end&&array[start]<standard){
start++;
}
if(start<end){//說明左邊找到了一個大於標準的數 就往右邊的坑填
array[end]=array[start];
end--;
}
}
array[start]=standard;//start==end 必定跳出循環 此時應該讓標準歸位到中間的位置
return start;
}
}

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