Heap Sort C language implementation

Source: Internet
Author: User

Heap sorting can be used as real-time sorting, is the original sort, does not require additional space, time complexity is O (NLGN), the best worst-case average is this, but is not stable ordering, the following is the C language implementation code:


//in order to simplify programming, the first position in a heap array element is not used.    struct heap {int size; int *arr;}    H;void max_heapify (struct heap * h, int p) {int largest;    int hsize = h->size;    int left = p * 2;    int right = p * 2 + 1;    if (left <= hsize && H->arr[left] > h->arr[p]) {largest = left;    } else {largest = P;    } if (right <= hsize && h->arr[right] > h->arr[largest]) {largest = right;        } if (largest! = p) {Swap (& (H->arr[p]), & (H->arr[largest]));    Max_heapify (h, largest);    }}void build_max_heap (struct heap * h) {int p = h->size/2;    while (P >= 1) {max_heapify (H, p--);    }}void heap_sort (struct heap *h, int n) {int i;    H->size = n;    Build_max_heap (h); for (i = 0; i < n; i++) {//always swaps the first element with the last element, noting that the first position in the array does not use Swap (& (H->arr[1]), & (H->arr[h        ->size]));        h->size--;    Max_heapify (H, 1); }}












Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Heap Sort C language implementation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.