zoukankan      html  css  js  c++  java
  • 八种排序整理(六)----堆排序

    基本概念:堆排序是一种特殊的树形数据结构,其每个节点都有一个值,通常提到的堆都是指一棵完全二叉树,

    根节点的值小于(或大于)两个子节点的值,同时根节点的两个子树也分别是一个堆。堆排序主要包括两个过程:

    一是构建堆, 二是交换堆顶元素与最后一个元素的位置。

    堆排序思想:
    1.   将序列构造成一棵完全二叉树 ;
    2.   把这棵普通的完全二叉树改造成堆,便可获取最小值 ;
    3.   输出最小值 ;
    4.   删除根结点,继续改造剩余树成堆,便可获取次小值 ;
    5.   输出次小值 ;
    6.   重复改造,输出次次小值、次次次小值,直至所有结点均输出,便得到一个排序 。

    堆排序的特点:

    稳  定  性:不稳定

    时间复杂度:O(nlogn)

    堆排序对记录较少的文件效果一般,但对于记录较多的文件很有效果,其运行时间主要耗费在创建堆与调整堆上。

     1 #include <iostream>
     2 
     3 using namespace std;
     4 
     5 void AdjustMinHeap(int *a, int pos, int len)
     6 {
     7     int temp;
     8     int child;
     9 
    10     for (temp = a[pos]; 2 * pos + 1 <= len; pos = child)
    11     {
    12         child = 2 * pos + 1; 
    13         if (child < len && a[child] > a[child + 1])
    14         {
    15             child++;
    16         }
    17         if (a[child] < temp)
    18         {
    19             a[pos] < a[child];
    20         }
    21         else
    22         {
    23             break;
    24         }
    25     }
    26     a[pos] = temp;
    27 }
    28 
    29 void Swap(int a, int b)
    30 {
    31     int temp;
    32     temp = a;
    33     a = b;
    34     b = temp;
    35 }
    36 
    37 void PrintArray(int *a, int length)
    38 {
    39     int i;
    40 
    41     for (i = 0; i < length; i++)
    42     {
    43         printf("%d ", a[i]);
    44     }
    45     printf("
    ");
    46 }
    47 
    48 void HeapSort(int *array, int len)
    49 {
    50     int i;
    51 
    52     for (i = len / 2 - 1; i >= 0; i--)
    53     {
    54         AdjustMinHeap(array, i, len - 1);
    55     }
    56     for (i = len -1; i >= 0; i--)
    57     {
    58         Swap(array[0], array[i]);
    59         AdjustMinHeap(array, 0, i - 1);
    60     }
    61 }
    62 
    63 int main()
    64 {
    65     int array[] = {0, 13, 1, 14, 27, 18};
    66     int length = sizeof(array) / sizeof(array[0]);
    67 
    68     HeapSort(array, length);
    69     PrintArray(array, length);
    70     while(1);
    71     return 0;
    72 }
  • 相关阅读:
    c++重载operator的示例 非原创
    L1-2 倒数第N个字符串 (15 分)真坑
    error C2955: “std::xx”: 使用 类 模板 需要 模板 参数列表
    时间超限问题处理(c++)
    C语言实验1
    心理魔术
    闰年作业
    20180425
    Labview学习笔记-条件结构的两个问题
    判断文件目录或者文件是否存在
  • 原文地址:https://www.cnblogs.com/kutoli/p/8337907.html
Copyright © 2011-2022 走看看