一个实现堆排序的源代码,
// HeapSort.cpp : Defines the entry point for the console application. // 实现堆排序 // CopyRight@ vine_branches, 22/08/2012 #include "stdafx.h" #include "stdio.h" #include <iostream> using namespace std; // HeapSort.cpp : Defines the entry point for the console application. // 实现堆排序 // CopyRight@ suhua, 22/08/2012 #include "stdafx.h" #include "stdio.h" #include <iostream> #include "assert.h" using namespace std; void HeapAjust(int *a, int i ,int size) { int max_ix = i; int done = 0; int min_id = 0; //从上往下 while( max_ix <= (size/2 -1) && (done!= 1)) { int left_child = 2*i+1; int right_child = 2*i +2 ; int min_value = 0; if (right_child <= size-1) { min_value = min(a[left_child], a[right_child]); min_id = (a[left_child]>a[right_child])?right_child:left_child; } else { min_value = a[left_child]; min_id = left_child; } if (a[max_ix] < min_value) { done = 1; } else { swap(a[min_id], a[max_ix]); } max_ix = min_id; } } void BuildHeap(int a[], int size) { //从最后一个非叶子节点开始,调整树 int i = size-1; int j = 0; int done = 0; assert(NULL != a); if (size < 0) { return ; } for (i = size -1; i >= 1; --i) { j = (i-1)/2; if (a[i] < a[j]) { swap(a[i], a[j]); HeapAjust(a, i, size); } } } void HeapSort(int a[], int size, int k) { int i; BuildHeap(a, k); for (i = k; i< size; ++i) { a[0] = a[i]; HeapAjust(a, 0, k); } } int _tmain(int argc, _TCHAR* argv[]) { int a[100] = {9, 16, 7, 3, 20, 17, 8, 45, 88,79,1,2,3}; int size = 13; int i; /*while (scanf("%d",&size)==1 && size>0) { for (i = 0; i < size; i++) cin >> a[i]; }*/ HeapSort(a, size, 7); for (i=1; i<= size; ++i) cout << a[i-1] <<" "; cout << endl; return 0; }