堆栈排序

来源:互联网 发布:java程序员必备工具 编辑:程序博客网 时间:2024/06/08 08:35

#include "stdafx.h"
#include <iostream>
using namespace std;

 

int count = 0;
void Swap(int &a,int &b)
 {
 int temp;
 temp = a;
 a = b;
 b = temp;
}//堆元素上移
void SiftUp(int H[],int i)
{
 bool done =false;
 if(i != 1)
 {
  while(!done && i !=1)
  {
   if(H[i]>H[i/2])
   {
     Swap(H[i],H[i/2]);
 
   }
   else done = true;
   i = i/2;
  }
 }
}
//堆元素下移
void SiftDown(int H[],int n,int i)//i为被下移元素的下标
{
   bool done = false;
   if((2*i)<=n)
   {
     while (!done && ( 2*i<=n))
  {  
   i =2*i;
         if(i+1<=n && H[i+1]>H[i])
      i = i+1;
     if(H[i/2]<H[i])
     {
      Swap(H[i/2],H[i]);
      count++;
     }

     else done = true;
  }
   }


}
//x为被插入元素的数
void Insert(int H[],int &n, int x)
{
   n = n+1;
   H[n] = x;
   SiftUp(H,n);
}
//建堆;n为数组的个数
void MakeHeap(int A[],int H[],int n) 
{
 int i,m = 0;
 for(i = 0;i <n; i++)
     Insert(H,m,A[i+1]);
 
}
//基于堆的排序
void HeapSort(int H[],int n)
{
  int i;
 
  for(i = n ;i >0;i--)
  {
      Swap(H[1],H[i]);
   count++;
  
   SiftDown(H,i-1,1);
  }

}

//该堆以数组下标为1开始
int main(int argc, char* argv[])
{
 int A[7] = {0,1,2,3,4,5,6};//A[0]不为栈的元素
 int H[7];
 MakeHeap(A ,H ,6);
 HeapSort(H ,6);
   for(int i = 1;i<7;i++)
    cout<<H[i]<<endl;
   cout<<"总共需要交换"<<count<<endl;
  
 return 0;
}

 

 

原创粉丝点击