挖坑法遞歸
void quicksort(int s[],int left,int right){
if(left<right){
int temp,i=left,j=right;
temp=s[right];
while(i<j){
//尋找左邊第一個大於基准值的下標
while(s[i]<=temp&&i<j)i++;
if(i<j)s[j--]=s[i];
//尋找右邊第一個小於基准值的下標
while(s[j]>=temp&&i<j)j--;
if(i<j)s[i++]=s[j];
}
s[i]=temp;
quicksort(s,left,i-1); //遞歸左邊部分數組
quicksort(s,i+1,right); //遞歸右邊部分數組
}
}
非遞歸(使用LinkedHashMap)
void quickSort1(int s[],int left,int right){
LinkedHashMap<Integer,Integer> lhp=new LinkedHashMap<>();
//將0,n放入LinkedHashMap
lhp.put(left,right);
while(!lhp.isEmpty()){ //只要有需要排序的段
//讀取left,right
Iterator<Map.Entry<Integer,Integer>> it=lhp.entrySet().iterator();
left=it.next().getKey();
right=lhp.get(left);
//並從LinkedHashMap中刪除
lhp.remove(left,right);
if(left>=right)continue;
int i=left,j=right,temp=s[right];
while(i<j){ //遍歷排序一遍
while(s[i]<=temp&&i<j)i++;
if(i<j)s[j--]=s[i];
while(s[j]>=temp&&i<j)j--;
if(i<j)s[i++]=s[j];
}
s[i]=temp;
lhp.put(left,i-1);
lhp.put(i+1,right);
}
}