堆排序的实现

#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);
    }
}

  

原文地址:https://www.cnblogs.com/usa007lhy/p/5512737.html