#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] << " "; } 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和代码应该不会不懂了!