八大排序算法--快速排序

快速排序

代码如下

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
#include <iostream>
using namespace std;
//挖坑填坑,分治

//挖坑填坑
//分
void mySwap(int &a,int &b){
    int tmp = a;
    a = b;
    b = tmp;
}

int partition(int start,int end,int a[]){
    //去中间为基准,将它与第一个元素交换
    //swap(a[start], a[(start+end)/2]);
    int i = start;
    int j = end;
    int x = a[start];
    while (i<j) {
        while (i<j&&a[j]>=x) {
            j--;
        }
        if (i<j) {
            //挖坑填坑
            a[i] = a[j];
            i++;
        }
        while (i<j&&a[i]<x) {
            i++;
        }
        if (i<j) {
            a[j] = a[i];
            j--;
        }
    }
    a[i] = x;
    return i;
}

//治
void quickSort(int low,int high,int a[]){
    if (low<high) {
        int p = partition(low, high, a);
        quickSort(low, p-1, a);
        quickSort(p+1, high, a);
    }
}


void QuickSort(int n,int a[]){
    quickSort(0, n-1, a);
}

int main(int argc, const char * argv[]) {
    int a[] = {1,4,2,8,7,9,6};
    QuickSort(7, a);
    for (int i=0; i<7; i++) {
        cout<<a[i]<<" ";
    }
    cout<<endl;
    return 0;
}

Comments