Heap sorting (Code 1)

Source: Internet
Author: User
#include <stdio.h>#include <stdlib.h>void build_heap(int data[], int);void adjust_heap(int data[], int);void heap_sort(int data[], int);int sub_max_heap(int data[], int, int);int main(int argc, char *argv[]){int i;int data[12] = {6, 10, 3, 5, 12, 8, 4, 23, 1, 2, 9, 7 };heap_sort(data, 12);for (i = 0; i < 12; ++i){printf("%d ", data[i]);}printf("\n");return 0;}void heap_sort(int data[], int num){int i = 1;build_heap(data, num);for (i = 1; i < num; ++i){int temp;temp = data[0];data[0] = data[num - i];data[num - i] = temp;adjust_heap(data, num - i);}}void build_heap(int data[], int num){int i, k, p;for (i = num / 2 - 1; i >= 0; --i){k = sub_max_heap(data, num, i);while (2 * k + 1 < num){p = k;k = sub_max_heap(data, num, p);}}}void adjust_heap(int data[], int num){int temp;int k, p;k = 0;while(2 * k + 1 < num){p = k;k = sub_max_heap(data, num, p);}}int sub_max_heap(int data[], int num, int i){int k;if (2 * i + 2 <= num - 1 && data[2 * i + 1] > data[2 * i + 2])k = 2 * i + 1;else if (2 * i + 2 <= num - 1)k = 2 * i + 2;elsek = 2 * i + 1;if (data[k] > data[i]){int temp;temp = data[k];data[k] = data[i];data[i] = temp;}return k;}/*int sub_max_heap(int data[], int num, int i){int largest;int l, r;l = 2 * i + 1;r = 2 * i + 2;if (l <= num - 1 && data[l] > data[i])largest = l;elselargest = i;if (r <= num - 1 && data[r] > data[largest])largest = r;if (largest != i){int temp;temp = data[i];data[i] = data[largest];data[largest] = temp;}return largest;}*/

 

Heap sorting (Code 1)

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.