import java.util.*;
/**
* 快排
*/
public class QuickSort {
/**
* 快排
* @param array
* @param low
* @param high
*/
public static void sort(int[] array, int low, int high) {
if (low >= high) {
return;
}
int pivot = partition(array, low, high);
sort(array, low, pivot - 1);
sort(array, pivot + 1, high);
}
/**
* 分区
* @param array
* @param low
* @param high
* @return
*/
private static int partition(int[] array, int low, int high) {
int left = low, right = high;
int pivot = left;
while (left < right) {
//从右向左扫描
while (array[right] >= array[pivot] && left < right) {
right--;
}
swap(array, right, pivot);
pivot = right;
//从左向右扫描
while (array[left] <= array[pivot] && left < right) {
left++;
}
swap(array, left, pivot);
pivot = left;
}
return pivot;
}
/**
* 元素交换
* @param array
* @param i
* @param j
*/
private static void swap(int[] array, int i, int j) {
int temp = array[i];
array[i] = array[j];
array[j] = temp;
}
public static void main(String args[]) {
int[] array = generateArray(10);
System.out.println("Original: " + Arrays.toString(array));
sort(array, 0, array.length - 1);
System.out.println("After Sort: " + Arrays.toString(array));
}
/**
* 生成随机数组
* @param length
* @return
*/
private static int[] generateArray(int length) {
Random random = new Random(31);
int[] array = new int[length];
Set<Integer> set = new HashSet<>(length);
for (int i = 0; i < length; i++) {
int value;
do {
value = random.nextInt(length);
} while (set.contains(value));
array[i] = value;
set.add(value);
}
return array;
}
}
排序 - 快排
最新推荐文章于 2022-03-19 22:01:23 发布