C++复习之堆排序&快速排序

来源:互联网 发布:抓涨停软件 编辑:程序博客网 时间:2024/04/28 01:40

堆是具有下列性质的完全二叉树 : 每个节点的值都大于或等于其左右孩子节点的值 , 称为大顶堆;或者每个节点的值都小于或等于其左右孩子节点的值 , 称为小顶堆 .堆排序就是利用堆进行排序的方法 .

基本思想是 : 将待排序的序列构造成一个大顶堆 . 此时 , 整个序列的最大值就是堆顶的根结点 . 将它移走 ( 其实就是将其与堆数组的末尾元素交换 , 此时末尾元素就是最大值 ), 然后将剩余的 n-1 个序列重新构造成一个堆 , 这样就会得到 n 个元素的次大值 . 如此反复执行 , 便能得到一个有序序列了.

时间复杂度为 O(nlogn), 好于冒泡 , 简单选择 , 直接插入的 O(n^2)

//  构造大顶堆#define leftChild(i) (2*(i) + 1)void percDown(int *arr, int i, int N) {    int tmp, child;    for (tmp = arr[i]; leftChild(i) < N; i = child) {        child = leftChild(i);        if (child != N - 1 && arr[child + 1] > arr[child])            child++;        if (arr[child] > tmp)            arr[i] = arr[child];        else            break;    }    arr[i] = tmp;}void HeapSort(int *arr, int N) {    int i;    for (i = N / 2; i >= 0; i--)        percDown(arr, i, N);    for (i = N - 1; i > 0; i--) {        swap1(&arr[0], &arr[i]);        percDown(arr, 0, i);    }}int main(void) {    int arr[] = { 9, 2, 5, 8, 3, 4, 7, 1, 6, 10 };    HeapSort(arr, 10);    for (int i = 0; i < 10; i++)        cout << arr[i] << ' ';    cout << endl;    return 0;}

一张图看懂堆排序
堆排序

快速排序

//快速排序一次划分算法partitionint partition(int *a, int first, int end) {    int i = first, j = end;    while (i < j) {        while (i < j && a[i] <= a[j])            j--;        if (i < j) {            swap1(&a[i], &a[j]);            i++;        }        while (i < j && a[i] < a[j]) {            i++;        }        if (i < j) {            swap1(&a[i], &a[j]);            j--;        }    }    return i;}//快速排序算法void quickSort(int *arr, int first, int end) {    if (first < end) {        int pivot = partition(arr, first, end);        quickSort(arr, first, pivot - 1);        quickSort(arr, pivot + 1, end);    }}
0 0