排序算法之快速排序

该算法在数组中选择一个称为主元的元素(pivot),将数组分为两部分,使得第一部分中的所有元素都小于或等于主元,第二部分中的所有元素都大于主元。对第一部分递归地应用快速排序,然后对第二部分递归的使用快速排序算法

 1 public class testQuickSort {
 2 
 3     public static void quickSort(int[] list) {
 4         quickSort(list, 0, list.length - 1);
 5     }
 6 
 7     private static void quickSort(int[] list, int first, int last) {
 8         if (last > first) {
 9             int pivotIndex = partition(list, first, last);
10             quickSort(list, first, pivotIndex - 1);
11             quickSort(list, pivotIndex + 1, last);
12         }
13     }
14 
15     // find pivot,Partition the array list(first...last)
16     private static int partition(int[] list, int first, int last) {
17         // choose the first elements as the pivot
18         int pivot = list[first];
19         // index for forward search
20         int low = first + 1;
21         // index for backward search
22         int high = last;
23         while (high>low) {
24             while (list[low] <= pivot && low <= high) {
25                 low++;
26             }
27             while (list[high] > pivot && low <= high) {
28                 high--;
29             }
30 
31             if (high > low) {
32                 int temp = list[high];
33                 list[high] = list[low];
34                 list[low] = temp;
35             }
36         }
37         while (high > first && list[high] >= pivot) {
38             high--;
39         }
40         if (pivot > list[high]) {
41             list[first] = list[high];
42             list[high] = pivot;
43             return high;
44         } else {
45             return first;
46         }
47     }
48 
49     public static void main(String[] args) {
50         int[] list = { 2, 3, 2, 5, 6, 1, -2, 3, 14, 12 };
51         quickSort(list);
52         for (int i = 0; i < list.length; i++) {
53             System.out.print(list[i] + " ");
54         }
55     }
56 }

方法partition使用主元划分为数组list[first...last],将子数组的第一个元素选为主元,在出事情况下,low指向字数组的第二个元素,而high指向子数组中最后一个元素。

快排时间:

  最坏情况下,划分由n个元素构成的数组需进行n次比较和n次移动。因此划分时间为O(N),每次主元会将数组划分为一个大的子数组和一个空数组。这个大的子规模是在上次划分的字数组的规模上减一,该算法需要(n-1)+(n-2)+...+2+1=O(n*n)

  最佳情况下,每次主元都将数组划分为规模大致相等的两部分。T(n) = T(n/2) + T(n/2) + n

      T(n) = O(n*logn)

  

原文地址:https://www.cnblogs.com/SamSarah/p/4902825.html