堆排序
1 //堆排序 2 #include <iostream> 3 #include <algorithm> 4 using namespace std; 5 void duipai1(int a[], int pos, int size) 6 { 7 int child; 8 int tmp = a[pos]; 9 for (;pos*2+1<size;pos=child) 10 { 11 child = pos * 2 + 1; 12 if (child!=size-1&&a[child+1]>a[child]) 13 { 14 child++; 15 } 16 if (a[child]>tmp) 17 { 18 a[pos] = a[child]; 19 } 20 else break; 21 } 22 a[pos] = tmp; 23 } 24 void duipai2(int a[], int size) 25 { 26 int i; 27 for (i=size/2-1;i>=0;i--) 28 { 29 duipai1(a, i, size); 30 } 31 for (i=size-1;i>0;i--) 32 { 33 swap(a[0], a[i]); 34 duipai1(a, 0, i); 35 } 36 } 37 int main() 38 { 39 int a[6] = { 1,6,3,5,2,0 }; 40 duipai2(a, 6); 41 for (auto x : a) 42 { 43 cout << x << " "; 44 } 45 return 0; 46 }
道阻且长,行则将至

浙公网安备 33010602011771号