堆排序算法的C/C++语言实现

#include<stdio.h>
/*
  Name: 
  Copyright: 
  Author: @dujianjian
  Date: 15/11/12 23:42
  Description: 小顶堆 
*/


void sift(int a[],int k,int m){
     int i = k,j = 2*i+1;
     int t = a[k];
     while(j < m){
             if(j<m-1 && a[j]>a[j+1])j++;
             if(t < a[j]){break;}
             else{a[i]=a[j];i = j;j = 2*i+1;}             
             }
     a[i]=t;
      
     } 
     
void Heapsort(int a[],int n){
          for(int i = n/2-1;i >= 0;i--)sift(a,i,n);
          
          for(int i = n-1 ;i >= 0;--i){
                int t = a[i];
                a[i] = a[0];
                a[0] = t;
                sift(a,0,i);
               // printf("aa\n");
                }
          }
          
int main(){
    //int a[10] = {5,9,8,7,2,6,1,0,3,4};
    int a[10]={4,1,3,2,16,9,10,14,8,7};
    for(int i = 0;i<10;i++)
     printf("%d ",a[i]);
     printf("\n");
      
     Heapsort(a, 10);
      
     for(int i = 0;i<10;i++)
     printf("%d ",a[i]);
     printf("\n");
    
    getchar();
    return 0;
    }
示例结果:

你可能感兴趣的:(堆排序算法的C/C++语言实现)