package sort.algorithm.quick;
public class Quick
{
// 快速排序的最坏情况运行时间是O(n^2),但快速排序的平均情况运行时间和最好情况运行时间都是O(nlogn)
public static void quicksort(int[] data, int first, int n)
{
int pivotIndex;
int n1;
int n2;
if (n>1)
{
pivotIndex = partition(data, first, n);
n1 = pivotIndex - first;
n2 = n - n1 -1;
quicksort(data, first, n1);
quicksort(data, pivotIndex + 1, n2);
}
}
private static int partition(int[] data, int first, int n)
{
int pivot = data[first]; // 作为中轴
int low = first;
int high = first + n -1;
while (low < high)
{
while (low < high && data[high] > pivot)
{
high--;
}
data[low] = data[high];
while (low < high && data[low] < pivot)
{
low++;
}
data[high] = data[low];
}
data[low] = pivot;
return low;
}
public static void main(String[] args)
{
int data[] = {80, 30, 60, 50, 40, 70, 20, 10, 5, 0};
quicksort(data,1,9);
for (int i = 0; i < data.length; i++)
{
System.out.print(data[i] + ",");
}
}
}
参考博文:Java实现快速排序
运行结果:
0,5,10,20,30,40,50,60,70,80,