算法思想:
快速排序使用分治法(Divide and conquer)策略来把一个串行(list)分为两个子串行(sub-lists)。
步骤为:
- 从数列中挑出一个元素,称为 "基准"(pivot),
- 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆在基准的后面(相同的数可以到任一边)。在这个分区退出之后,该基准就处于数列的中间位置。这个称为分区(partition)操作。
- 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。
递归的最底部情形,是数列的大小是零或一,也就是永远都已经被排序好了。虽然一直递归下去,但是这个算法总会退出,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。
请参考维基百科的更详细解释:http://zh.wikipedia.org/wiki/%E5%BF%AB%E9%80%9F%E6%8E%92%E5%BA%8F
本算法使用递归实现,并且取数组中最右边的值作为中枢值,代码如下所示:
import java.util.Random;
/**
* quick sort implementation, always use the right most item in array as pivot
*
* @author Sun Kui
*/
public class QuickSort1 {
private long[] theArr;
private int nElems;
public QuickSort1(int max) {
theArr = new long[max];
nElems = 0;
}
public void insert(long value) {
theArr[nElems++] = value;
}
public void display() {
System.out.print("A=");
for (int i = 0; i < nElems; i++) {
System.out.print(theArr[i] + " ");
}
System.out.println();
}
public void quickSort() {
this.recQuickSort(0, nElems - 1);
}
public void recQuickSort(int left, int right) {
if (right - left <= 0) {
return;
} else {
long pivot = theArr[right];
int partition = partitionIt(left, right, pivot);
recQuickSort(left, partition - 1);
recQuickSort(partition + 1, right);
}
}
public int partitionIt(int left, int right, long pivot) {
int leftPtr = left - 1;
// right most item is not included, it's used as pivot
// and will be put into right position after partition.
int rightPtr = right;
while (true) {
while (theArr[++leftPtr] < pivot) {
// NOP
}
while (rightPtr > 0 && theArr[--rightPtr] > pivot) {
//NOP
}
if (leftPtr >= rightPtr) {
// here is the position of pivot
break;
} else {
swap(leftPtr, rightPtr);
}
}
// put pivot int the right position
swap(leftPtr, right);
return leftPtr;
}
public void swap(int dex1, int dex2) {
long temp = theArr[dex1];
theArr[dex1] = theArr[dex2];
theArr[dex2] = temp;
}
public static void main(String... args) {
if (args.length < 1) {
System.out.println("Usage: java QuickSort1 number");
return;
}
Random rand = new Random();
int count = Integer.parseInt(args[0]);
QuickSort1 qs = new QuickSort1(count);
for (int i = 0; i < count; i++) {
qs.insert(rand.nextInt(count * count));
}
qs.display();
qs.quickSort();
qs.display();
}
}
end.