2路归并排序

#define _CRT_SECURE_NO_WARNINGS
#include 
#include 
#include 
#include 

#define MAXSIZE 20
typedef int DATATYPE;

typedef struct seqList
{
	DATATYPE data[MAXSIZE];
	int length;
}SeqList;
//初始化顺序表
void InitSeqList(SeqList* list)
{
	for (int i = 0; i < MAXSIZE; i++)
	{
		list->data[i] = 0;
	}
	list->length = 0;
}
//创建顺序表
void CreateSeqList(SeqList* list)
{
	DATATYPE data, length;
	printf("请输入要创建的顺序表的长度:");
	scanf_s("%d", &length);
	printf("请输入数据:");
	for (int i = 1; i <= length; i++)
	{
		scanf_s("%d", &data);
		list->data[i] = data;
		list->length++;
	}
}

//2路归并
void Merge(SeqList* list, int low, int mid, int high)
{
	//辅助数组
	SeqList list1;
	InitSeqList(&list1);
	//标记左半子表未排序的第一个元素
	int l_pos = low;
	//标记右半子表未排序的第一个元素
	int r_pos = mid + 1;
	//辅助数组的下标
	int pos = low;

	//合并
	while (l_pos <= mid && r_pos <= high)
	{
		if (list->data[l_pos] <= list->data[r_pos])//左半子表的元素更小
		{
			list1.data[pos++] = list->data[l_pos++];
		}
		else//右半子表的元素更小
		{
			list1.data[pos++] = list->data[r_pos++];
		}
	}
	//当退出循环时可能左半子表或右半子表有剩余元素
	//当左半子表有剩余,合并左半子表剩余元素
	while (l_pos <= mid)
	{
		list1.data[pos++] = list->data[l_pos++];
	}
	//当右半子表有剩余,合并右半子表剩余元素
	while (r_pos <= high)
	{
		list1.data[pos++] = list->data[r_pos++];
	}
	//将临时数组中的数据重新写到list中
	while(low <= high)
	{
		list->data[low] = list1.data[low];
		low++;
	}
}
//2路归并排序
void TwoMergeSort(SeqList* list, int low, int high)
{
	//当只有一个元素时不需要在进行划分,只有一个元素的区域本身就有序了,只需要进行归并即可
	if (low < high)
	{
		//找中间结点
		int mid = (low + high) / 2;
		//递归划分左子表
		TwoMergeSort(list, low, mid);
		//递归划分右子表
		TwoMergeSort(list, mid + 1, high);
		//归并已经排序的部分
		Merge(list, low, mid, high);
	}
}
//打印
void PrintfSeqList(SeqList* list)
{
	for (int i = 1; i <= list->length; i++)
	{
		printf("%6d", list->data[i]);
	}
	printf("\n");
}
int main(void)
{
	SeqList list;
	
	//2路归并排序
	printf("--------------------2路归并排序--------------------\n");
	InitSeqList(&list);
	CreateSeqList(&list);
	PrintfSeqList(&list);
	TwoMergeSort(&list,1,list.length);
	printf("2路归并排序得到的排序序列为:");
	PrintfSeqList(&list);


	system("pause");
	return EXIT_SUCCESS;
}

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