第一、演算法原理
針對數組中的一個數(這個數叫做pivot),將這個數組劃分成兩個部分:左邊的每個元素都比pivot小;右邊的每個元素都比pivot大。然後,再分別在左右兩個部分遞迴地進行這種劃分的操作。
如此說比較籠統,在這個大方向上實際上是隱含著兩個重要的地方:
1、如何確定pivot
2、如何劃分
至於如何確定pivot這點先預設認為是取數組中的第一個元素,在下文將會針對取pivot,提出提高效率的方案。而至於如何劃分,這點需要在這裡馬上說明。
在這裡的劃分,是基於兩個元素的位置交換實現的。而需要互換的兩個元素有這樣的特點,就左邊的元素的值比pivot的要大,而右邊的元素的值比pivot要小。
代碼實現+解釋(解釋使用英文,因為想進外企,努力訓練英文中)
public class SortTest<E extends Comparable<E>> {
public ArrayList<E> quicksort(ArrayList<E> arraylist) {
ArrayList<E> ret = null;
if (arraylist == null || arraylist.size() == 0) {
throw new IllegalArgumentException();
}
subquicksort(0, arraylist.size() - 1, arraylist);
ret = arraylist;
return ret;
}
public void subquicksort(int begin, int end, ArrayList<E> arraylist) {
ArrayList<E> ret = null;
if (begin < end) {
// by default,use the first item of the array as the pivot
E pivotkey = arraylist.get(begin);
// i is the monitor of the current left-side item
int i = begin;
//j is the right-side monitor
//why set j as "end+1" not end?
//because in the coming snippet:
//while (j > begin && arraylist.get(--j).compareTo(pivotkey) >= 0)
//;
//If we do not do like that way,like,we use j++ instead,we will get
//the wrong index afterward.
int j = end + 1;
while (true) {
//We can look over the items that are smaller than pivot and
//let the i come to item that is bigger than pivot.
while (i < end && arraylist.get(++i).compareTo(pivotkey) <= 0)
;
//It's just like the last sentence
while (j > begin && arraylist.get(--j).compareTo(pivotkey) >= 0)
;
if (i >= j) {// let the j be the position for the pivot
break;
} else {
swap(i, j, arraylist);
}
}
//the j th item still stores the value smaller than pivot.
swap(begin, j, arraylist);
//recurse
subquicksort(begin, j - 1, arraylist);
subquicksort(j + 1, end, arraylist);
}
}
public void swap(int i, int j, ArrayList<E> arraylist) {
E temp;
temp = arraylist.get(j);
arraylist.set(j, arraylist.get(i));
arraylist.set(i, temp);
}
}