A1098 Insertion or Heap Sort [堆排序]

在这里插入图片描述
堆排序,先不断向下调整建最大堆,然后堆排序

#include<iostream>
#include<vector>
#include<queue>
#include<stack>
#include<string>
#include<math.h>
#include<algorithm>
using namespace std;

bool judge(int a[], int b[], int n)
{
	for (int i = 1; i <= n; i++)
	{
		if (a[i] != b[i])
			return false;
	}
	return true;
}

bool insert_sort(int a[],int b[],int n)
{
	int i, j;
	for (i = 2; i <=n; i++)
	{
		int temp = a[i];
		for (j = i; j - 1 >= 1 && temp < a[j - 1];j--)
		{
			a[j] = a[j - 1];
		}
		a[j] = temp;
		if (judge(a, b, n))
		{
			i++;
			int temp = a[i];
			for (j = i; j - 1 >= 1 && temp < a[j - 1]; j--)
			{
				a[j] = a[j - 1];
			}
			a[j] = temp;
			return true;
		}
	}
	return false;
}

void downAdjust(int low, int high,int a[])
{
	int i = low, j = i * 2;
	while (j <= high)
	{
		if (j + 1 <= high && a[j + 1] > a[j])
			j = j + 1;
		if (a[j] > a[i])
		{
			swap(a[j], a[i]);
			i = j;
			j = i * 2;
		}
		else
			break;
	}
}

bool heap_sort(int a[], int b[], int n)
{
	for (int i = n / 2; i >= 1; i--)
	{
		downAdjust(i, n, a);
	}
	for (int i = n; i > 1; i--)
	{
		swap(a[i], a[1]);
		downAdjust(1, i - 1, a);
		if (judge(a, b, n))
		{
			i--;
			swap(a[i], a[1]);
			downAdjust(1, i - 1, a);
			return true;
		}
	}
	return false;
}

void showarray(int a[], int n)
{
	for (int i = 1; i <= n; i++)
	{
		cout << a[i];
		if (i < n) cout << " ";
	}
}

int main()
{
	int n; int a[101], b[101], c[101];
	cin >> n;
	for (int i = 1; i <= n; i++)
	{
		cin >> a[i];
		b[i] = a[i];
	}
	for (int i = 1; i <= n; i++)
	{
		cin >> c[i];
	}
	if (insert_sort(b, c, n))
	{
		cout << "Insertion Sort" << endl;
		showarray(b, n);
	}
	if(heap_sort(a,c,n))
	{
		cout << "Heap Sort" << endl;
		showarray(a, n);
	}
}


posted @ 2020-07-28 13:32  _Hsiung  阅读(51)  评论(0编辑  收藏  举报