原作者:http://blog.csdn.net/u013144863/article/details/53236230#java
原本想在下面评论的,但是代码过长,只好重新写一篇博客。
import java.util.Random;
/**
*
*
* @author wangqingxin
*
*/
public class QuickSort {
public static void main(String[] args) {
Random ran = new Random();
//int[] sort = { 34, 38, 49, 32, 7, 41, 42, 8, 34, 24 };
int[] sort=new int[10];
for (int i = 0; i < 10; i++) {
sort[i] = ran.nextInt(50);
}
System.out.print("排序前的数组为");
for (int i : sort) {
System.out.print(i + " ");
}
//quickSort_wqx(sort, 0, sort.length - 1);
quickSort(sort, 0, sort.length - 1);
System.out.println("");
System.out.print("排序后的数组为");
for (int i : sort) {
System.out.print(i + " ");
}
}
/**
* 快速排序
*
* 最优解
*/
public static void quickSort(int[] a, int low, int high) {
//递归快速排序
int pivotLoc = 0;//中心点
if (low < high) {
pivotLoc = partitionLoc(a, low, high);
quickSort(a, low, pivotLoc-1);
quickSort(a, pivotLoc+1, high);
}
}
//获取到a的下标 low ~ high 中, a[low]的应该放的位置, 即左边的数 < a[low] 右边的数 > a[low]
private static int partitionLoc(int[] a, int low, int high) {
// a[0] = a[low];
int key = a[low];
while (low < high) {
while (low < high && a[high] >= key) {
high--;
}
a[low] = a[high];
while (low < high && a[low] <= key) {
low++;
}
a[high] = a[low];
}
a[low] = key;
return low;
}
}