堆栈排序

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

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是使用 C++ 实现堆栈排序的示例代码: ```cpp #include <iostream> #include <stack> using namespace std; void sortStack(stack<int>& s) { stack<int> tmpStack; while (!s.empty()) { int tmp = s.top(); s.pop(); while (!tmpStack.empty() && tmpStack.top() < tmp) { s.push(tmpStack.top()); tmpStack.pop(); } tmpStack.push(tmp); } while (!tmpStack.empty()) { s.push(tmpStack.top()); tmpStack.pop(); } } int main() { stack<int> s; s.push(3); s.push(2); s.push(4); s.push(1); s.push(5); cout << "Before sorting: "; while (!s.empty()) { cout << s.top() << " "; s.pop(); } cout << endl; s.push(3); s.push(2); s.push(4); s.push(1); s.push(5); sortStack(s); cout << "After sorting: "; while (!s.empty()) { cout << s.top() << " "; s.pop(); } cout << endl; return 0; } ``` 该程序中,我们首先定义了一个 `sortStack` 函数,它接受一个堆栈作为参数。函数内部我们创建了一个辅助栈 `tmpStack`,然后遍历原栈,将原栈的元素逐个取出,并将它们插入到辅助栈中。如果插入的元素比辅助栈顶的元素小,就将辅助栈的元素弹出,并将它们插入原栈中,直到插入的元素比辅助栈顶的元素大为止。这样就可以保证辅助栈中的元素是按照从大到小的顺序排列的。最后,我们再将辅助栈中的元素逐个弹出,插入到原栈中,这样就完成了排序。 在主函数中,我们首先创建了一个堆栈 `s`,并向其中插入了一些元素。然后,我们打印出排序前的堆栈元素,调用 `sortStack` 函数对堆栈进行排序,最后再次打印出排序后的堆栈元素。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值