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

     1 #include <iostream>
     2 using namespace std;
     3 
     4 void HeapAdjust(int Array[],int s ,int m);
     5 void HeapSort(int Array[],int Length)
     6 {
     7     for(int i = Length/2 ;i>0;i--)
     8     {
     9         HeapAdjust(Array,i,Length);
    10     }
    11 
    12     for(int j =Length ;j>1 ;j-- )
    13     {
    14         int temp;
    15         temp = Array[j];
    16         Array[j] = Array[1];
    17         Array[1] = temp;
    18         HeapAdjust(Array,1,j-1);
    19     }
    20 }
    21 void HeapAdjust(int Array[],int s ,int m)
    22 {
    23     int temp = Array[s];
    24     for(int i = 2*s  ; i <= m ; i = i*2)
    25     {
    26         if(Array[i]<Array[i+1] && i<m) //这里面的i<m 保证了i+1不越界
    27         {
    28             ++i;
    29         }
    30         if(temp >= Array[i])
    31             break;
    32         Array[s] = Array[i];
    33         s = i;
    34     }
    35     Array[s] = temp;//简便在这次交换
    36 }
    37 
    38 int main()
    39 {
    40 
    41     int a[6] = {0,4,3,6,2,1};
    42     for(int i =0 ;i<5; i++)
    43     {
    44         printf("%d ",a[i]);
    45     }
    46     printf("/n ");
    47     HeapSort(a,5);
    48     for(int i =0 ;i<5; i++)
    49     {
    50         printf("%d ",a[i]);
    51     }
    52     system("pause");
    53 }

    方法是没问题,但是上面的主函数写错了,因为上面写的是从下标为1开始的,数组的时候,要小心是不是有零

  • 相关阅读:
    Redux API之applyMiddleware
    Redux API之combineReducers
    Redux API之creatStore
    Redux API之Store
    React-Redux之API
    ES6之6种遍历对象属性的方法
    React库protypes属性
    js立即执行函数
    Collection与Map总结
    02-再探MySQL数据库
  • 原文地址:https://www.cnblogs.com/xiaochige/p/8486227.html
Copyright © 2011-2022 走看看