合并排序-顺序表-两路合并排序迭代算法

合并排序-顺序表-两路合并排序迭代算法_第1张图片

合并排序-顺序表-两路合并排序迭代算法_第2张图片

#include
#include
#define MAXSIZE 100
typedef int T;
typedef struct list {
	int size;
	T elements[MAXSIZE];
}List;
void Merge(List* lst, T temp[], int i1, int j1, int i2, int j2, int* k) {
	int _i1 = i1;
	int _i2 = i2;
	while ( _i1<=j1 &&  _i2<=j2)
	{
		if (lst->elements[_i1] <= lst->elements[_i2] )
		{
			temp[(*k)++] = lst->elements[_i1++];
		}
		else {
			temp[(*k)++] = lst->elements[_i2++];
		}
	}
	while (_i1 <= j1)
	{
		temp[(*k)++] = lst->elements[_i1++];
	}
	while (_i2 <= j2)
	{
		temp[(*k)++] = lst->elements[_i2++];
	}
}
void MergeSort(List *lst) {
	T temp[MAXSIZE];
	int i1, j1, i2, j2, i, k, size = 1;
	while (size<lst->size)
	{
		i1 = 0; k = 0;
		while (i1+size < lst->size)
		{
			i2 = i1 + size;
			j1 = i2 - 1;
			if (i2+size-1 > lst->size -1)
			{
				j2 = lst->size - 1;
			}
			else {
				j2 = i2 + size - 1;
			}
			Merge(lst, temp, i1, j1, i2, j2, &k);
			i1 = j2 + 1;
		}
		for ( i = 0; i < k ; i++)
		{
			lst->elements[i] = temp[i];
		}
		size *= 2;
	}
}
void main() {
	int i;
	List* lst = (List*)malloc(sizeof(List));
	lst->size = 9;
	lst->elements[0] = 56;
	lst->elements[1] = 25;
	lst->elements[2] = 35;
	lst->elements[3] = 42;
	lst->elements[4] = 73;
	lst->elements[5] = 66;
	lst->elements[6] = 46;
	lst->elements[7] = 30;
	lst->elements[8] = 52;
	MergeSort(lst);
	for (i = 0; i < 9; i++)
	{
		printf("%d \n", lst->elements[i]);
	}
}

result:

25
30
35
42
46
52
56
66
73

你可能感兴趣的:(算法,排序算法,c语言)