package com.lstc.sort;
/**
* 快速排序算法实现:
* 时间效率:快速排序算法的运行时间依赖于划分是否平衡,即根据枢轴元素 pivot
* 将序列划分为两个子序列中的元素个数,而划分是否平衡又依赖于所使用的枢轴元素。下面我们 在不同的情况下来分析快速排序的渐进时间复杂度。
*
* 快速排序的最坏情况是每次进行划分时,在所得到的两个子序列中有一个子序列为空。O(n^2)
* 快速排序的最好情况是在每次划分时,都将序列一分为二,正好在序列中间将序列分成长度相等的两个子序列 O(nlogn)
* 快速排序需要一个堆栈来实现递归.若每次划分都将 序列均匀分割为长度相近的两个子序列,则堆栈的最大深度为 logn,但是,在最坏的情况 下,堆栈的最大深度为 n.
*
* @author wf
*
*/
public class QuickSort {
public static void main(String[] args) {
int[] a = { 9, 3, 5, 1, 0, 8, 2, 4, 7, 6 };
// 排序之前的序列
print(a);
// 调用快速排序方法
quickSort(a, 0, a.length - 1);
// 排完序之后输出数组验证是否正确排序
print(a);
}
/**
* 实现一次划分的过程
*
* @param a
* 数组元素数组a
* @param low
* 划分序列区间[low...high]
* @param high
* @return 返回枢纽元素的位置
*/
public static int FindPos(int[] a, int low, int high) {
int pivot = a[low];// 使用a[low](第一个元素)作为枢纽元素
while (low < high) {// 从两端交替向内扫描
while (low < high && a[high] > pivot)
high--;
a[low] = a[high];// 将比pivot(枢纽值)小的元素向前移动
while (low < high && a[low] < pivot)
low++;
a[high] = a[low];// 将比pivot(枢纽值)大的元素向后移动
}// 终止while循环之后low和high一定是相等的
a[low] = pivot;// 设置枢纽(中间剩余的那个元素)
return low;// 返回枢纽元素位置,可以是high,但不能返回pivot,a[low],a[high]
}
// 在划分算法的基础上,快速排序算法的递归实现算法如下
public static void quickSort(int[] a, int low, int high) {
int pos;// 声明获取枢纽元素的位置变量
if (low < high) {
pos = FindPos(a, low, high);// 先对表进行划分:一分为二
quickSort(a, low, pos - 1);// 对左边的表进行递归排序
quickSort(a, pos + 1, high);// 对右边的表进行递归排序
}
}
// 输出数组元素的方法
public static void print(int[] a) {
for (int i = 0; i < a.length; i++) {
System.out.print(a[i] + "\t");
}
System.out.println();//换行
}
}
Java实现快速排序
最新推荐文章于 2024-01-02 14:03:12 发布