插入排序------直接插入排序(2)

        思路:先将第1个记录视为一个有序的记录序列,然后从第2个记录开始,依次将未排序的记录插入这个有序的记录序列中,直到整个文件中的记录全部排序完毕。

#include<stdio.h>
#include<assert.h>
typedef int ElemType;
struct ForSort
{
	ElemType elem;
};

void DirectInsertionSort(ForSort *arr,int n)
{
	assert(arr != NULL);
	assert(n > 0);

	int i, j;
	ForSort temp;
	for (i = 1; i < n; ++i)
	{
		j = i;
		temp = arr[j];
		while (j > 0 && temp.elem < arr[j - 1].elem)
		{
			arr[j] = arr[j - 1];
			j--;
		}
		arr[j] = temp;
	}
}

int main()
{
	ForSort arr[] = { 98,78,76,65,54,32,12 };
	int n = sizeof(arr) / sizeof(ForSort);
	DirectInsertionSort(arr, n);
	for (int i = 0; i < n; i++)
		printf("%-4d", arr[i].elem);
	return 0;
}
本程序在VS2017下运行通过

猜你喜欢

转载自blog.csdn.net/qq_41822235/article/details/80704322