堆排序练习(手痒)

来源:互联网 发布:类似itools的软件 编辑:程序博客网 时间:2024/06/02 19:43
#include <iostream>using namespace std;void Sift(int r[], int k, int m);          //筛选法调整堆void HeapSort(int r[], int n);             //堆排序void Swap(int &i,int &j,int &temp);        //引用交换int main(){int i;int r[9] = {0,36,30,18,40,32,45,22,50};//r[0]用作交换操作的暂存单位    cout<<"待排序序列:"<<endl;for(i = 1;i < 9;i++)cout<<r[i]<<" ";cout<<endl;    HeapSort(r,8);cout<<"排序后的序列(升序):"<<endl;for(i = 1;i < 9;i++)cout<<r[i]<<" ";cout<<endl;return 0;}void Sift(int r[], int k, int m){int i = k;int j = 2*i;while (j <= m){if(j < m && r[j] < r[j+1]) j++;        if(r[i] > r[j]) break;else {Swap(r[i],r[j],r[0]);i = j;j = 2 * i;}}}void HeapSort(int r[],int n)         //n为元素个数{int i;for(i = n/2; i >= 1; i--)Sift(r,i,n);for(i = 1;i < n; i++){Swap(r[1],r[n-i+1],r[0]);Sift(r,1,n-i);}}void Swap(int &i,int &j,int &temp){temp = i;i = j;j = temp;}

0 0
原创粉丝点击