2021-01堆排序


//Heap.h
#pragma once
#include<vector>
#include<iostream>

using namespace std;
enum HeapType
{
	Big, Small
};
enum ChildPos
{
	Left, Right
};
const int Invalid = -1;
const size_t MAXSIZE = 200;


class Heap {
private:

	int m_type;
	int* m_arr=nullptr;
	int m_size;

	void ithNodeDownAdjust(int i,int arrLen);
	//调整的前提是下面的堆本就满足规则
	int getWinner(int lchild, int rchild);
	void buildHeap();
public:
	Heap();
	Heap(const vector<int>& v, int type = 1);
	~Heap() {
		delete m_arr;
		m_arr = nullptr;
	}

	//func

	int getTop() {
		return m_arr[0];
	}

	int popTop() {
		int ans = m_arr[0];
		m_arr[0] = m_arr[m_size - 1];
		ithNodeDownAdjust(0, --m_size);
		return ans;
	}
	void sort() {
		int endi = m_size - 1;
		while (endi) {
			swap(m_arr[0], m_arr[endi]);
			ithNodeDownAdjust(0, endi);
			--endi;
		}
	}

	void show() {
		for (int i = 0; i < m_size;++i) {
			cout << m_arr[i] << " ";
		}
		cout<<endl;
	}
};

Heap::Heap()
{
	m_type = Small;
	m_size = 0;
	m_arr = nullptr;
}


Heap::Heap(const vector<int>& v, int type)
{
	int v_len = v.size();
	if (v_len > MAXSIZE) {
		printf_s("too many numbers!\n");
		return;
	}
	m_arr = (int*)malloc(MAXSIZE * sizeof(int));
	for (int i = 0; i < v_len; ++i) {
		m_arr[i] = v.at(i);
	}
	m_type = type;
	m_size = v_len;
	buildHeap();

}
void 
Heap::buildHeap()
{
	for (int i = m_size / 2 - 1; i >= 0; --i) {
		ithNodeDownAdjust(i, m_size);
	}
}

void 
Heap::ithNodeDownAdjust(int i,int arrLen)
{
	int l_i = 2 * i + 1;
	if (l_i >= arrLen) return;
	int r_i = 2 * i + 2;
	
	int lchild = (l_i < arrLen) ? m_arr[l_i] :Invalid ;
	int rchild = (r_i < arrLen) ? m_arr[r_i] :Invalid ;
	int winner = getWinner(lchild, rchild);


	int oldData = m_arr[i];
	if (winner==Left) {
		if (m_type==Small) {
			if (oldData < lchild) {
				return;
			}
			else {
				swap(m_arr[i], m_arr[l_i]);
				ithNodeDownAdjust(l_i,arrLen);
			}
		}
		else {
			if (oldData > lchild) {
				return;
			}
			else {
				swap(m_arr[i], m_arr[l_i]);
				ithNodeDownAdjust(l_i,arrLen);
			}
		}
	}
	else {
		if (m_type == Small) {
			if (oldData < rchild) {
				return;
			}
			else {
				swap(m_arr[i], m_arr[r_i]);
				ithNodeDownAdjust(r_i,arrLen);
			}
		}
		else {
			if (oldData > rchild) {
				return;
			}
			else {
				swap(m_arr[i], m_arr[r_i]);
				ithNodeDownAdjust(r_i,arrLen);
			}
		}
	}
}

int 
Heap::getWinner(int lc, int rc)
{
	if (lc == Invalid) return Right;
	if (rc == Invalid) return Left;
	if (m_type==Small) {
		if (lc < rc) {
			return Left;
		}
		else
			return Right;
	}
	else {
		if (lc > rc) {
			return Left;
		}
		else
			return Right;
	}
}


//main.cpp

#include"Heap.h"


void test_heap() {
	vector<int> v = { 1,13,9,7,298,92,74,0};
	Heap heap(v,Big);
	cout << heap.getTop() << endl;

	heap.sort();
	heap.show();
}
int main() {

	test_heap();
	system("pause");
	return 0;
}






猜你喜欢

转载自blog.csdn.net/qq_34890856/article/details/112420748