快速排序适合数据比较多的排序。如果数据比较少,不如使用插入排序。
java源码在Arrarys.sort() 这个方法中,一个排序算法写了几千行。。。真不是我等凡人能写的。源码中写的是用两个中枢数进行运算。我能力有限就在这里简单实现一下。
package sort.quick;
import java.lang.reflect.Array;
import java.util.Arrays;
public class QuickSort
{
public static void swap(int[] arr,int low,int high) {
int temp = arr[low];
arr[low] = arr[high];
arr[high] = temp;
}
//可以减少不必要的交换 swap
public static int partition(int[] arr ,int low,int high) {
int pivotKey ;//中枢树设为子表第一个数 并不是0
// pivotKey = arr[low];
// 可以对 pivotKey 进行优化 三数取中
int m = low + (high - low)/2;
if(arr[low]>arr[high])
swap(arr, low, high);
if(arr[m]>arr[high])
swap(arr, m, high);
if(arr[m]>arr[low])
swap(arr, m, low);
pivotKey = arr[low];
while(low<high) {
while(low<high&&arr[high]>=pivotKey)
high--;
swap(arr, low, high);
while(low<high&&arr[low]<=pivotKey)
low++;
swap(arr, low, high);
}
return low;
}
public static void qSort(int[] arr, int low ,int high) {
int pivot = 0;
if(low<high) {
pivot = partition(arr, low, high); //返回得到中枢值所在的index
qSort(arr,low,pivot-1);
qSort(arr, pivot+1, high);
}
}
public static void main(String[] args) {
int [] arr = {50,10,90,30,70,40,80,60,20};
int [] arr2 = {50,10,90,30,70,40,80,60,20};
int low = 0;
int high = arr.length-1;
partition(arr, low, high);
for(int i=0 ; i<arr.length ; i++)
System.out.print(arr[i]+" ");
System.out.println();
qSort(arr2, 0, arr.length-1);
for(int i=0 ; i<arr.length ; i++)
System.out.print(arr2[i]+" ");
}
}
下面是源码中的简单介绍
/**
* Sorts the specified array into ascending numerical order.
*
* <p>Implementation note: The sorting algorithm is a Dual-Pivot Quicksort
* by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm
* offers O(n log(n)) performance on many data sets that cause other
* quicksorts to degrade to quadratic performance, and is typically
* faster than traditional (one-pivot) Quicksort implementations.
*
* @param a the array to be sorted
*/