• 简单堆排序


    简单堆排序

     1 #include <iostream>
     2 #include <cstdlib>
     3 #include <ctime>
     4 #define Father(N) ((N - 1) >> 1)
     5 #define Left(N) ((N << 1) + 1)
     6 #define Right(N) ((N + 1) << 1)
     7 using namespace std;
     8 
     9 #define VectorMax 10
    10 int vector[VectorMax];
    11 void heapSort(int *vector, const int length);
    12 void print(int *vector, const int length);
    13 int main()
    14 {
    15     srand(time(NULL));
    16     for (int i = 0; i < VectorMax; i++)
    17         vector[i] = rand() % 1000;
    18     heapSort(vector, VectorMax);
    19     return 0;
    20 }
    21 
    22 void print(int *vec, int length) 
    23 {
    24     for (int i = 0; i < length; i++)
    25         cout << vec[i] << " ";
    26     cout << endl;
    27 }
    28 void swap(int &a, int &b)
    29 {
    30     int tmp = a;
    31     a = b;
    32     b = tmp;
    33 } /*build Heap */ 
    34 void buildHeap(int *vec, int length)
    35 {
    36     for (int i = 1; i < length; i++) {
    37         int N = i;
    38         while (N > 0) {
    39             int father = Father(N);
    40             if (vec[father] > vec[N])
    41                 swap(vec[father], vec[N]);
    42             N = father;
    43         }
    44     }
    45 }                /*adjust Heap */
    46 
    47 void adjustHeap(int *vec, const int length)
    48 {
    49     int N = 0;
    50     int top = vec[0];
    51     while (N < length && Left(N) < length) {
    52         const int left = Left(N), right = Right(N);
    53         if (right >= length) {    /*if right exceed length */
    54             if (top > vec[left])
    55                 vec[N] = vec[left], N = left;
    56             break;
    57         }
    58         if (vec[left] > top && vec[right] > top)    /*select the small one */
    59             break;
    60         int nextN = vec[left] < vec[right] ? left : right;
    61         vec[N] = vec[nextN];
    62         N = nextN;
    63     } vec[N] = top;
    64 }
    65 void heapSort(int *vec, const int length)
    66 {
    67     buildHeap(vec, length);
    68     for (int i = length - 1; i > 0; i--) {    /*swap vec[0] and vec[heap_size-1] */
    69         swap(vec[0], vec[i]);    /*each for, the length of vec subtract 1 */
    70         adjustHeap(vec, i);
    71     } print(vec, length);
    72 }
  • 相关阅读:
    [zt]petshop4.0 详解之二
    HOW TO: Implement a DataSet JOIN helper class in Visual C# .NET(DataSetHelper)
    DVGPrinter 设置列宽
    [转载]ASP.NET 的学习流程
    初级版FAQ
    [转]PetShop的系统架构设计(1)
    [zt] petshop4.0 详解之三
    mssql2000 jdbc驱动设置
    自动设置环境变量
    Ubuntu中VirtualBox不能使用USB(此法不通)
  • 原文地址:https://www.cnblogs.com/-lee/p/4254082.html
Copyright © 2020-2023  润新知