堆排序
#include <vector> #include <iostream> using namespace std; //最大堆 void adjust(int i, vector<int>& array,int length) { while (i >= 0 && i < length / 2) { int max = i; if (2 * i + 1 < length) { max = array[i] > array[2 * i + 1] ? i : 2 * i + 1; } if (2 * i + 2 < length) { max = array[max] > array[2 * i + 2] ? max : 2 * i + 2; } if (max != i) { int tmp = array[i]; array[i] = array[max]; array[max] = tmp; i = max; } else { break; } } } void heapSort(vector<int>& array,int length) { for (int i = length / 2 - 1;i >= 0;i--) { adjust(i, array, length); } for (int i = 0;i < length -1;i++) { int tmp = array[0]; array[0] = array[length - 1-i]; array[length - 1 - i] = tmp; adjust(0, array, length - 1 - i); } } int main(void) { vector<int> array = { 49, 38, 65, 97, 76, 13, 27, 49 }; int length = array.size(); heapSort(array, length); for (int i= 0;i < length;i++) { cout << array[i] << " "; } system("pause"); }
作者:严彦彪
原创作品转载请注明出处