标签:堆排序
第一次实现堆排序,花了近两个小时。
主要还是堆调整,原理网上很多,直接给出运行代码和结果:
代码:
#include <iostream> using namespace std; void adjustHeap(int number[],int k,int length){ int t=number[k]; int i; for(; k*2+1 < length; k=i){ i=k*2+1; if(number[i] < number[i+1] && i<length-1){ i++; } if(number[i] > number[k]){ number[k]=number[i]; number[i]=t; // }else{ break; } } } void buildMaxHeap(int number[],int length){ int i= (length>>1)-1; for(;i >= 0;i--){ adjustHeap(number,i,length); } } void heapSort(int number[],int length){ buildMaxHeap(number,length); for(int i=length-1; i>=0 ;i --){ int temp=number[length-1]; number[length-1] = number[0]; number[0] = temp; adjustHeap(number,0,--length); } } int main(){ int input[8]={2,1,4,3,99,100,56,909}; heapSort(input,8); for(int i=0;i<8;i++){ cout<< input[i] <<" "; } return 0; }
标签:堆排序
原文地址:http://blog.csdn.net/buyingfei8888/article/details/38323445