您的位置:首页 > 其它

堆排序

2014-04-22 14:35 405 查看
  


#include <iostream>
#define len(x) (unsigned int)sizeof(x)/sizeof(x[0])

using namespace std;

void Swap(int x[],int i,int j){
//    int tem = x[i];
//    x[i] = x[j];
//    x[j] = tem;
//
//    x[i]^=x[j];
//    x[j]^=x[i];
//    x[i]^=x[j];
x[i] = x[i]+x[j];
x[j] = x[i]-x[j];
x[i] = x[i]-x[j];
}

void print(int x[],int length){
for(int i = 0; i < length; i++){
cout << x[i] << "\t";
}
cout <<endl;
}

/*heapSort Area*/

void maxHeapify(int r[],int heapSize,int index){
int left = 2*index+1;
int right = 2*index+2;
int larger = index;
if(r[larger] < r[left] && left < heapSize) {//不能有left=heapSize
larger = left;
}else larger = index;
if(r[larger] < r[right] && right < heapSize){//不能有left=heapSize
larger = right;
}
if(larger!=index){
Swap(r,larger,index);
maxHeapify(r,heapSize,larger);
}
}

int lastNode(int index){
if(index/2==0) return (index-1)/2;
else return (index-2)/2;
}

void buildMaxHeap(int r[],int heapSize){
for(int i = lastNode(heapSize); i >= 0; i --){
maxHeapify(r,heapSize,i);
}
}

void heapSort(int r[],int length){
int heapSize = length;
buildMaxHeap(r,length);
for(int i = heapSize - 1; i > 0; i--){
Swap(r,0,heapSize-1);
cout << r[heapSize-1] << " is put at !" << heapSize-1 << endl;
heapSize = heapSize-1;
maxHeapify(r,heapSize,0);
}
}

int main()
{
int r[] = {6,7,2,3,8,4,1,9,5,0};
print(r,len(r));
heapSort(r,len(r));
print(r,len(r));
return 0;
}


  看了这个ppt和代码应该不会不懂了!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: