数据结构 09-排序3 Insertion or Heap Sort(C语言)

According to Wikipedia:

Insertion sort iterates, consuming one input element each repetition, and growing a sorted output list. Each iteration, insertion sort removes one element from the input data, finds the location it belongs within the sorted list, and inserts it there. It repeats until no input elements remain.

Heap sort divides its input into a sorted and an unsorted region, and it iteratively shrinks the unsorted region by extracting the largest element and moving that to the sorted region. it involves the use of a heap data structure rather than a linear-time search to find the maximum.

Now given the initial sequence of integers, together with a sequence which is a result of several iterations of some sorting method, can you tell which sorting method we are using?

Sample Input 1:

10
3 1 2 8 7 5 9 4 6 0
1 2 3 7 8 5 9 4 6 0

Sample Output 1:

Insertion Sort
1 2 3 5 7 8 9 4 6 0

Sample Input 2:

10
3 1 2 8 7 5 9 4 6 0
6 4 5 1 0 3 2 7 8 9

Sample Output 2:

Heap Sort
5 4 3 1 0 2 6 7 8 9

code

# include 

int n;
typedef enum { Insertion, Heap } sortMethod;
int initialSeq[110];
int sortSeq[110];


int orderedlength()
{
	for (int i = 0; i < n - 1; i++)
	{
		if (sortSeq[i] > sortSeq[i + 1]) return i + 1;
	}
	return n;
}

void distinguish(sortMethod & M, int & iteration)
{
	// 判断排序类型

	int p = orderedlength();
	int i;
	for (i = p; i < n; ++i)
		if (sortSeq[i] != initialSeq[i]) break;

	if (i == n) M = Insertion;
	else M = Heap;


	// 计算排到第几趟了
	if (M == Insertion)
	{
		iteration = p;
	}
	else
	{
		
		for (int i = n; i > 0; --i)
		{
			if (sortSeq[i-1] < sortSeq[0]) 
			{
				iteration = i; // 堆中待排元素的个数
				break;
			}
		}
	}
}


void InsertionSortGoOn(int iteration)
{
	int X = sortSeq[iteration], i;
	for (i = iteration; i > 0 && sortSeq[i - 1] > X; --i)
	{
		sortSeq[i] = sortSeq[i - 1];
	}
	sortSeq[i] = X;
}

void HeapSortGoOn(int iteration)
{
	int X = sortSeq[iteration - 1];
	sortSeq[iteration - 1] = sortSeq[0];

	// 大顶堆,X下滤,保证左右孩子的最大值小于X
	int child = 0;
	int parent;
	for (; child * 2 < iteration - 1; child = parent)
	{
		parent = child * 2 + 1; //从0起存的heap,左孩子是2i+1,右孩子是2i+2
		if (parent + 1 < iteration - 1 && sortSeq[parent + 1] > sortSeq[parent]) parent++;
		if (sortSeq[parent] > X) sortSeq[child] = sortSeq[parent];
		else break;
	}
	sortSeq[child] = X;
}

int main(void)
{
	scanf("%d\n", &n);
	for (int i = 0; i < n; ++i) scanf("%d", &initialSeq[i]);
	for (int i = 0; i < n; ++i) scanf("%d", &sortSeq[i]);
	sortMethod M;
	int iteration;
	distinguish(M, iteration);
	if (M == Insertion)
	{
		printf("Insertion Sort\n");
		InsertionSortGoOn(iteration);
	}
	else
	{
		printf("Heap Sort\n");
		HeapSortGoOn(iteration);
	}

	for (int i = 0; i < n; ++i)
		printf("%d%s", sortSeq[i], i==n-1?"\n":" ");

	return 0;
}

你可能感兴趣的:(ZJU数据结构,数据结构,算法)