zoukankan      html  css  js  c++  java
  • 排序-堆排序

     1 #include<iostream>
     2 using namespace std;
     3 
     4 void swap(int arr[], int i, int j)
     5 {
     6     int temp = arr[i];
     7     arr[i] = arr[j];
     8     arr[j] = temp;
     9 }
    10 
    11 void heapify(int tree[], int n, int i)//n是结点总数,i是调整的结点数组下标
    12 {
    13     //函数heapify对元素tree[i]进行调整
    14     if (i >= n)
    15     {
    16         return;        //递归出口
    17     }
    18 
    19     int c1 = 2 * i + 1;
    20     int c2 = 2 * i + 2;
    21     int max = i;
    22     if (c1<n&&tree[c1]>tree[max])
    23     {
    24         max = c1;
    25     }
    26     if (c2<n&&tree[c2]>tree[max])
    27     {
    28         max = c2;
    29     }
    30     if (max != i)
    31     {
    32         swap(tree, max, i);
    33         heapify(tree, n, max);    //对下面的结点继续调整
    34     }
    35 }
    36 
    37 void build_heap(int tree[], int n)    //建立大根堆
    38 {
    39     int last_node = n - 1;
    40     int parent = (last_node - 1) / 2;    //找到最后一个非叶子结点
    41     int i;
    42     for (i = parent; i >= 0; i--)    //不断向上调整
    43     {
    44         heapify(tree, n, i);
    45     }
    46 }
    47 
    48 void heap_sort(int tree[], int n)    //堆排序
    49 {
    50     build_heap(tree, n);
    51     int i;
    52     for (i = n - 1; i >= 0; i--)
    53     {
    54         swap(tree, i, 0);
    55         heapify(tree, i, 0);//由于每次都会减少一个最大值结点,故用i
    56     }
    57 }
    58 int main()
    59 {
    60     int tree[] = { 4,10,2,5,1,3,8,7,1};
    61     int n = 9;
    62     //heapify(tree, n, 0);
    63     //build_heap(tree, n);
    64     heap_sort(tree, n);
    65     
    66     for (int i = 0; i < n; i++)
    67     {
    68         cout << tree[i] << endl;
    69     }
    70 
    71     system("pause");
    72 }
  • 相关阅读:
    Spring配置文件中别名的使用
    Spring IOC容器创建对象的方式
    sass安装及使用
    word转html 压缩图片网站
    Yarn 和 Npm 命令行切换 摘录
    react生命周期
    event事件
    Flex 布局
    YYYY-mm-dd HH:MM:SS 时间格式
    页面按钮埋点+跟踪location.search
  • 原文地址:https://www.cnblogs.com/KBryant/p/11629097.html
Copyright © 2011-2022 走看看