快排的原理是,讓一個數做爲中間值A,使得左邊的數都小於(大於)等於A,右邊的數都大於(小於)A。算法
1 public static void quickSort(Integer[] arrayList,int begin,int end){ 2 if(begin>=end) 3 return; 4 int par=paration3(arrayList, begin, end); 5 if(begin<par-1) 6 quickSort(arrayList, begin, par-1); 7 if (par<end) 8 quickSort(arrayList, par+1, end); 9 }
public static int paration(Integer[] arrayList,int begin,int end){ int temp=arrayList[begin]; while (begin<end) { while (begin<end&&arrayList[end]>temp) { end--; } if (begin<end) { arrayList[begin]=arrayList[end]; begin++; } while (begin<end&&arrayList[begin]<temp) { begin++; } if (begin<end) { arrayList[end]=arrayList[begin]; end--; } } arrayList[begin]=temp; return begin; }
通常來講,遞歸算法均可以用非遞歸來實現,添加一個棧, 保存相關信息便可。快速排序的非遞歸算法亦是如此,每次保存下下次須要排序的。ui
public static void quickSort2(Integer[] arrayList,int begin,int end){ int par=paration3(arrayList, begin, end); Stack<Integer> stack=new Stack<Integer>(); if(begin>par-1){ stack.push(begin); stack.push(par-1); } if(par+1<end){ stack.push(par+1); stack.push(end); } while (!stack.empty()) { end=stack.pop(); begin=stack.pop(); par=paration3(arrayList, begin, end); if(begin<par-1){ stack.push(begin); stack.push(par-1); } if(par+1<end){ stack.push(par+1); stack.push(end); } } }