首页 > 代码库 > 堆排序(代码1)
堆排序(代码1)
#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; else k = 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; else largest = 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;}*/
堆排序(代码1)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。