package xxx;
public class QuickSort {
/**
* 划分数组,返回POS,使得POS左边不大于POS,POS右边不小于POS
*/
public int split(int[] array, int low, int high) {
int cur = array[low];
// 当low==high时,找到POS
while (low < high) {
// 右边不小于POS
while (low < high && array[high] >= cur)
high--;
array[low] = array[high];
// 左边不大于POS
while (low < high && array[low] <= cur)
low++;
array[high] = array[low];
}
// 找到POS
array[low] = cur;
return low;
}
/**
* 对array[low, high]进行快速排序
*/
public void quickSort(int[] array, int low, int high) {
// 递归条件
if (low < high) {
// 划分得到两个子问题
int pos = split(array, low, high);
// 分别求解两个子问题
quickSort(array, low, pos - 1);
quickSort(array, pos + 1, high);
}
}
public static void main(String[] args) {
int[] array = new int[16];
java.util.Random random = new java.util.Random();
for (int i = 0; i < array.length; i++)
array[i] = random.nextInt(1000);
System.out.println("排序前:");
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
new QuickSort().quickSort(array, 0, array.length - 1);
System.out.println("排序后:");
for (int i = 0; i < array.length; i++)
System.out.print(array[i] + " ");
System.out.println();
}
}
快速排序程序
最新推荐文章于 2018-04-24 22:02:57 发布