堆排序C++實現
阿新 • • 發佈:2020-07-14
#ifndef HeapSort_hpp #define HeapSort_hpp #include <stdio.h> #include <vector> using namespace std; class HeapSort { public: void sort(vector<int>& arr, int len) { //1、構件大頂堆 for(int i = len/2 - 1;i >= 0; i--) { //從第一個非葉子節點,從下至上,從右至左調整結構 adjustHeap(arr, i, len); } //2、調整堆結構,交換堆頂元素與末尾元素 for(int j = len-1; j > 0; j--) { //交換堆頂元素和尾元素 swap(arr, 0, j); //重新對堆進行調整 adjustHeap(arr, 0, j); } } void adjustHeap(vector<int>& arr, int i, int len) { int temp = arr[i];//暫存當前待調整元素 //從i節點的左子節點開始,也就是2i+1處開始 for (int k = 2*i+1; k < len; k = k*2+1) { //如果左子節點小於右子節點,k指向右子節點 if (k + 1 < len && arr[k] < arr[k+1]) { k++; } //如果子節點大於父節點,將子節點賦值給父節點 if (arr[k] > temp) { arr[i] = arr[k]; i = k; }else { break; } } arr[i] = temp;//將temp值放到最終位置 } void swap(vector<int>& arr, int aIndex, int bIndex) { int temp = arr[aIndex]; arr[aIndex] = arr[bIndex]; arr[bIndex] = temp; } }; #endif /* HeapSort_hpp */ /*HeapSort.hpp*/ #include "HeapSort.hpp" /*mian.cpp*/ #include "HeapSort.hpp" #include <iostream> #include <vector> using namespace std; int main(int argc, const char * argv[]) { vector<int> arr7 = {7, 5, 3, 2, 4, 9, 1, 8, 0, 6}; cout << "arr7: " << endl; for (int item : arr7) { cout << item <<" "; } cout << endl; HeapSort heapSort = HeapSort(); heapSort.sort(arr7, int(arr7.size())); cout << "heap sort arr7: " << endl; for (int item : arr7) { cout << item <<" "; } cout << endl; return 0; }