zoukankan      html  css  js  c++  java
  • 堆排序的实现

    #include<iostream>
    using namespace std;
    
    void display(int *a, int size){
        for(int i = 0 ; i < size; i++){
            cout << a[i] << " ";
        }
        cout << endl;
    }
    
    void heapSort(int *a, int i, int size){
         int lc = 2*i,rc = 2*i+1,max = i;
         if(lc <= size && a[max-1] < a[lc-1]){
              max = lc;
         }
          if(rc <= size && a[max-1] < a[rc-1]){
             max = rc;
          }
          if(max != i){
             swap(a[i-1],a[max-1]);
             if(2*max <= size){
                 heapSort(a,max,size);
             }
          }
    }
    
    void buildHeap(int *a, int size){
        for(int i = size/2;i > 0; i-- ){
            heapSort(a,i,size);
        }
    }
    
    
    int main(){
        int a[] = {16,7,3,20,17,8};
        int size = 6;
        buildHeap(a,size);
    
        swap(a[0],a[size]);
        size--;
        while(size>1){
            heapSort(a,1,size);
            swap(a[0],a[size]);
            size--;
        }
    
    //    while(--size>0){
    //        swap(a[0],a[size]);
    //        heapSort(a,1,size);
    //    }
        display(a,6);
        return 0;
    
    }
    

      注释部分对上面的优化。

    堆排序的php实现:

    <?php
    $x = array(72,6,57,88,60,42,83,73,48,85);//待排序数组
    $x = array(0,72,6,57,88,60,42,83,73,48,85);//为了排序方便,将数组第一个元素设为0,不用
    $len = count($x)-1;
    buildHeap($x,$len);
    swap($x,1,$len);
    $len--;
    while($len > 1){
        heapAdjust($x,1,$len);
        swap($x,1,$len);
        $len--;
    }
    displayHeap($x);
    function displayHeap($x){
        foreach($x as $value){
            echo $value." ";
        }
        echo "<br>";
    }
    function swap(&$x,$i,$j){
        $tmp = $x[$i];
        $x[$i] = $x[$j];
        $x[$j] = $tmp;
    }
    
    function buildHeap(&$x,$len){
        for($i = $len/2; $i > 0; $i--){
            heapAdjust($x,$i,$len);
        }
    }
    
    function heapAdjust(&$x,$i,$len){
        $maxNum = 2*$i;
        if($maxNum > $len){
            return;
        }
        if($maxNum+1<=$len && $x[$maxNum+1] > $x[$maxNum]){
            $maxNum++;
        }
        if($x[$i] < $x[$maxNum]){
            swap($x,$i,$maxNum);
            heapAdjust($x,$maxNum,$len);
        }
    }
    

      

  • 相关阅读:
    转载--重写、覆盖、重载、多态几个概念的区别分析
    笔试题--奇虎360-2013
    转载---数据挖掘十大经典算法
    Nginx的启动、停止与重启
    程序员的十种级别,看看你属于哪一种?
    C标签的用法
    eclipse修改代码后都需要clean的解决办法
    创建一个jFinal项目
    java redirect用法
    java获取访问者真实的IP地址
  • 原文地址:https://www.cnblogs.com/usa007lhy/p/5512737.html
Copyright © 2011-2022 走看看