pivot
下面是快速排序 Java 实现示例。
public class QuickSortExample
{
public static void main(String[] args)
{
// 下面是一个无序的数组
Integer[] array = new Integer[] { 12, 13, 24, 10, 3, 6, 90, 70 };
// 使用快排来给他排序
quickSort( array, 0, array.length - 1 );
// 输出并验证排序结果
System.out.println(Arrays.toString(array));
}
public static void quickSort(Integer[] arr, int low, int high)
{
//检查空数组
if (arr == null || arr.length == 0){
return;
}
if (low >= high){
return;
}
//从列表中间获取pivot元素
int middle = low + (high - low) / 2;
int pivot = arr[middle];
// 让 left < pivot 并且 right > pivot
int i = low, j = high;
while (i <= j)
{
//检查左侧数组上的所有值是否低于pivot
while (arr[i] < pivot)
{
i++;
}
//检查直到左侧数组上的所有值都大于pivot
while (arr[j] > pivot)
{
j--;
}
//现在比较列表两边的值,看看它们是否需要交换
//交换后,在两个列表上移动迭代器
if (i <= j)
{
swap (arr, i, j);
i++;
j--;
}
}
//递归地执行与上面相同的操作以对两个子数组进行排序
if (low < j){
quickSort(arr, low, j);
}
if (high > i){
quickSort(arr, i, high);
}
}
public static void swap (Integer array[], int x, int y)
{
int temp = array[x];
array[x] = array[y];
array[y] = temp;
}
}
[3, 6, 10, 12, 13, 24, 70, 90]
在 Java 中,Arrays.sort()
方法使用快速排序算法对使用双pivot元素的原语数组进行排序。双pivot使该算法更加快速。https://www.leftso.com/article/1115.html