建堆,堆排序,堆维护
#include <iostream> using namespace std; //num is the number of the array,index from 0 to num-1 //the index relationship : child index is k then parent index is (k-2)/2 void shiftDown(int * an, int i, int num) { if(NULL == an || i < 0 || num < 0) return; int temp = an[i]; while(2*i+1 < num) { int index = 2 * i + 1; if(index+1 < num) { if(an[index] < an[index+1]) index++; } if(temp < an[index]) { an[i] = an[index]; i = index; } else break; } an[i] = temp; } void heapSort(int * an, int num) // heapSort is O(nlogn) { for(int i = (num-2)/2; i >= 0; --i) //build heap O(n) shiftDown(an, i, num); for(int j = num-1; j >= 0; --j) //sort n*log(n) { int temp = an[0]; an[0] = an[j]; an[j] = temp; shiftDown(an, 0, j); } } void shiftUp(int * an, int newIndex) { if(NULL == an || newIndex < 0) return; int temp = an[newIndex]; int parent = (newIndex-1)/2; while( parent >= 0) { if(temp > an[parent]) { an[newIndex] = an[parent]; newIndex = parent; parent = (newIndex-1)/2; } else break; } an[newIndex] = temp; } int main() { int N; while(cin >> N) { int * arr = new int[N]; for(int i = 0; i < N; ++i) cin >> arr[i]; heapSort(arr, N); for(int j = 1; j <= 4; ++j) cout << arr[N-j] << endl; delete arr; } return 0; }