堆排序
//
// Created by Administrator on 2021/8/1.
//
#ifndef C__TEST01_HEAPSORTED_HPP
#define C__TEST01_HEAPSORTED_HPP
#include <vector>
#include <iostream>
using namespace std;
class HeapSorted {
public:
HeapSorted(vector<int> An);
void swap(vector<int> &A, int pos1, int pos2);
void heapInsert(vector<int> &A, int index);
void heapify(vector<int> &A, int index, int heapSize);
void heapSortedAlgrorithm(vector<int> &A);
private:
vector<int> A;
};
HeapSorted::HeapSorted(vector<int> An) :
A(An){
A.resize(An.size());
}
void HeapSorted::swap(vector<int> &A, int pos1, int pos2) {
if(pos1 < 0 || pos2 < 0 ||
pos1>A.size()-1 || pos2 > A.size()-1){
return;
}
int temp = A[pos1];
A[pos1] = A[pos2];
A[pos2] = temp;
}
void HeapSorted::heapInsert(vector<int> &A, int index) {
//lchild or rchild:n,father:(n-1)/2
while(A[index] > A[(index-1)/2] && index>=0){
swap(A, index, (index-1)/2);
index = (index-1)/2;
}
}
void HeapSorted::heapify(vector<int> &A, int index, int heapSize) {
//father:n, lchild:2n+1,rchild:2n+2
int left = 2*index+1; //lchild
while(left < heapSize){
int largeSize = (left+1<heapSize) &&
(A[left] < A[left+1]) ? (left+1):left;
largeSize = A[index] < A[largeSize]?largeSize:index;
if(largeSize == index){
break;
}
swap(A, index, largeSize);
index = largeSize;
left = 2*index+1; //lchild
}
}
void HeapSorted::heapSortedAlgrorithm(vector<int> &A) {
if(A.empty() || A.size()<2){
return;
}
for(int i = 0; i<A.size();i++){
heapInsert(A,i);
}
int heapSize = A.size();
swap(A, 0, --heapSize);
while (heapSize>0){
heapify(A, 0, heapSize);
swap(A, 0, --heapSize);
}
}
#endif //C__TEST01_HEAPSORTED_HPP
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈