递归分治算法(二)-快速排序算法
递归分治算法(二)-快速排序算法
https://www.cnblogs.com/fanwencong/p/5910958.html
前言:
快速排序由C. A. R. Hoare在1962年提出。它的基本思想是:首先从待排序序列中选一个关键字作为枢轴,使枢轴左边的所有数据都小于这个枢轴,枢轴右边的数据都大于这个枢轴,再用递归的方法对这两个子序列进行快速排序,最终使得整个序列有序
JAVA代码如下:
package guibing;
/***
* @author 文聪
* @date 2016/09/26 快速排序算法
**/
public class QuickSort {
public static void main(String[] args) {
int arr[]={40,30,68,98,86,15,57};
quickSort(arr, 0, arr.length-1);
for (int i : arr) {
System.out.print(i+" ");
}
}
public static void quickSort(int[] nums, int low, int high) {
if (low < high) {
int dp = partition(nums, low, high);
quickSort(nums, low, dp - 1);
quickSort(nums, dp + 1, high);
}
}
public static int partition(int[] nums, int low, int high) {
int pivot = nums[low];
while (low < high) {
while (low < high && nums[high] >= pivot)
high--;
nums[low] = nums[high];
while (low < high && nums[low] <= pivot)
low++;
nums[high] = nums[low];
}
nums[low] = pivot;// 此时low等于high,所以,也可以写成nums[high]=pivot;
return low; // 此时low等于high,所以返回任意一个都是正确的 }
}
}
总结:
快速排序 对冒泡排序的改进 首先选一个轴值,将待排序记录分割成独立的两部分, 左侧记录的关键字均小于或者等于轴值,右边记录的关键字均大于或者等于轴值, 然后分别对这两部分重复上述过程,直到整个序列有序。 在最好情况下,每次划分轴值的左侧子序列与右侧子序列的长度相同,时间复杂度为O(nlogn), 在最坏情况下,待排序序列为正序或逆序,时间复杂度为O(n^2);平均情况下,时间复杂度为O(nlogn)。
其实在比较上篇文章的时候就会发现归并排序和快速排序的思想差不多的,归并排序是分开小的子序列在排序,而快速排序是排序后再分开为两个子序列在排序,都采用了递归分治的思想,有异曲同工之妙。
« 上一篇:递归分治算法(一)-归并排序算法
» 下一篇:我的校招(2017届)面经之路
QQ交流群:494389786 个人网站:www.fanwencong.com




浙公网安备 33010602011771号