您的位置:首页 > 其它

【排序算法】快速排序

2015-08-28 09:41 225 查看
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,
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: