以下是手動實現(xiàn)C++的堆排序的代碼示例:
#include <iostream>
#include <vector>
void heapify(std::vector<int>& arr, int n, int i) {
int largest = i;
int left = 2*i + 1;
int right = 2*i + 2;
if (left < n && arr[left] > arr[largest])
largest = left;
if (right < n && arr[right] > arr[largest])
largest = right;
if (largest != i) {
std::swap(arr[i], arr[largest]);
heapify(arr, n, largest);
}
}
void heapSort(std::vector<int>& arr) {
int n = arr.size();
for (int i = n/2 - 1; i >= 0; i--)
heapify(arr, n, i);
for (int i = n-1; i >= 0; i--) {
std::swap(arr[0], arr[i]);
heapify(arr, i, 0);
}
}
int main() {
std::vector<int> arr = {12, 11, 13, 5, 6, 7};
heapSort(arr);
std::cout << "Sorted array is: ";
for (int i = 0; i < arr.size(); i++)
std::cout << arr[i] << " ";
std::cout << std::endl;
return 0;
}
在以上代碼中,我們首先定義了一個heapify
函數(shù)用于調(diào)整堆,然后定義了一個heapSort
函數(shù)用于進行堆排序。在main
函數(shù)中,我們初始化一個包含一些整數(shù)的數(shù)組,然后調(diào)用heapSort
函數(shù)對數(shù)組進行排序,并輸出排序后的結(jié)果。