浙江大学数据结构MOOC-课后习题-第九讲-排序3 Insertion or Heap Sort

题目汇总
浙江大学数据结构MOOC-课后习题-拼题A-代码分享-2024

题目描述

测试点

思路分析

和上一题的思路一样,每进行一次迭代,来验证当前序列是否和给定的序列相同

代码展示

cpp 复制代码
#include <cstdlib>
#include <iostream>
#define MAXSIZE 100
typedef int ElementType;

void swap(int A[], int i, int j)
{
	int temp = A[i];
	A[i] = A[j];
	A[j] = temp;
}

void print(int A[], int N)
{
	for (int i = 0; i < N; i++)
	{
		if (i == 0)
			std::cout << A[i];
		else
			std::cout << ' ' << A[i];
	}
}
bool isSame(int A[], int input[], int N)
{
	for (int i = 0; i < N; i++)
	{
		if (A[i] != input[i])
			return false;
	}
	return true;
}
bool insertion_Sort(int A[], int input[], int N)
{
	/* 算法 */
	int i, j, temp;
	bool flag = false;
	for (i = 1; i < N; i++)
	{	

		temp = A[i];	/* 摸牌 */
		for (j = i; j > 0 && A[j - 1] > temp; j--)
			A[j] = A[j - 1];
		A[j] = temp;

		if (flag == true)
		{
			print(A, N);
			return true;;
		}
		if (isSame(A, input, N))
		{
			std::cout << "Insertion Sort" << std::endl;
			flag = true;
		}
	}
	return false;
}

void percDown(int A[], int p, int N)
{
	/* 将N个元素的数组中以A[p]为根的子堆调整为最大堆 */
	int parent, child;
	int temp = A[p];
	for (parent = p; (parent * 2 + 1) < N; parent = child)
	{
		child = parent * 2 + 1;
		/* child指向左右孩子中较大者 */
		if (child != N - 1 && A[child] < A[child + 1])
			child++;
		if (temp > A[child]) break;
		else A[parent] = A[child];
	}
	A[parent] = temp;
}
void heap_Sort(int A[], int input[], int N)
{	
	bool flag = false;	
	/* 建立大根堆 */
	for (int i = N - 1; i >= 0; i--)
		percDown(A, i, N);
	/* 删除最大值 */
	for (int i = N - 1; i >= 0; i--)
	{
		swap(A, 0, i);
		percDown(A, 0, i);
		if (flag == true)
		{
			print(A, N);
			return;
		}
		if (isSame(A, input, N))
		{
			std::cout << "Heap Sort" << std::endl;
			flag = true;
		}
	}
}
void check(int A[], int input[], int N)
{
	int copyA[MAXSIZE];
	for (int i = 0; i < N; i++)
		copyA[i] = A[i];
	if (insertion_Sort(copyA, input, N))
		return;
	else
	{
		for (int i = 0; i < N; i++)
			copyA[i] = A[i];
		heap_Sort(copyA, input, N);
		return;
	}
}

int main()
{
	int A[MAXSIZE];
	int input[MAXSIZE];
	int N;

	std::cin >> N;
	for (int i = 0; i < N; i++)
		std::cin >> A[i];
	for (int i = 0; i < N; i++)
		std::cin >> input[i];

	check(A, input, N);
	return 0;
}
相关推荐
vir0239 分钟前
P1928 外星密码(dfs)
java·数据结构·算法·深度优先·1024程序员节
胡萝卜3.01 小时前
C++ list核心接口与实战技巧
数据结构·c++·list·list使用
仟千意1 小时前
数据结构:排序篇
数据结构
脚踏实地的大梦想家3 小时前
【Go】P8 Go 语言核心数据结构:深入解析切片 (Slice)
开发语言·数据结构·golang
蒙奇D索大4 小时前
【数据结构】数据结构核心考点:AVL树删除操作详解(附平衡旋转实例)
数据结构·笔记·考研·学习方法·改行学it·1024程序员节
大数据张老师7 小时前
数据结构——平衡二叉树
数据结构·算法·查找
大数据张老师8 小时前
数据结构——BF算法
数据结构·算法·1024程序员节
Yupureki8 小时前
从零开始的C++学习生活 14:map/set的使用和封装
c语言·数据结构·c++·学习·visual studio·1024程序员节
一匹电信狗8 小时前
【LeetCode_876_2.02】快慢指针在链表中的简单应用
c语言·数据结构·c++·算法·leetcode·链表·stl
胖咕噜的稞达鸭8 小时前
算法入门---专题二:滑动窗口2(最大连续1的个数,无重复字符的最长子串 )
c语言·数据结构·c++·算法·推荐算法·1024程序员节