码迷,mamicode.com
首页 > 编程语言 > 详细

快速排序

时间:2015-04-08 12:33:42      阅读:121      评论:0      收藏:0      [点我收藏+]

标签:

基本思想:

通过一趟排序将待排序记录分割成独立的两部分,其中一部分记录的关键字均比另一部分关键字小,则分别对这两部分继续进行排序,直到整个序列有序。

技术分享

 

复杂度分析:

时间复杂度:O(nlgn)(平均),O(nlgn)(最好),O(n^2)(最坏)

空间复杂度:O(nlgn)

稳定性:不稳定

Java实现:

 1 import java.util.Arrays;
 2 
 3 public class QuickSort {
 4     
 5     public static int partition(int[] num, int low, int high) {
 6         if(num == null || low < 0 || high >= num.length) {
 7             return -1;
 8         }
 9         int pivotkey = num[low];
10         //枢轴选定后永远不变,最终在中间,前小后大
11         while(low < high) {
12             while(low < high && num[high] > pivotkey) high--;
13             //将比枢轴小的元素移到低端,此时high位相当于空,等待低位比pivotkey大的数补上
14             num[low] = num[high];
15             while(low < high && num[low] < pivotkey) low++;
16             //将比枢轴大的元素移到高端,此时low位相当于空,等待高位比pivotkey小的数补上
17             num[high] = num[low];
18         }
19         //当low == high,完成一趟快速排序,此时low位相当于空,等待pivotkey补上
20         num[low] = pivotkey;
21         return low;
22     }
23     
24     public static void quickSort(int[] num, int low, int high) {
25         if(low == high) {
26             return;
27         }
28         int pivot;
29         if(low < high) {
30             //pivot作为枢轴,较之小的元素在低位,较之大的元素在高位
31             pivot = partition(num, low, high);
32             //对前后数组递归调用快速排序,直到顺序完全正确
33             quickSort(num, low, pivot - 1);
34             quickSort(num, pivot + 1, high);
35         }
36     }
37     public static void main(String[] args) {
38         int[] array = {49,38,65,97,76,13,27};
39         quickSort(array, 0, array.length - 1);
40         System.out.println(Arrays.toString(array));
41     }
42 }

 

快速排序

标签:

原文地址:http://www.cnblogs.com/ivanyangzhi/p/4401966.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!