插入算法(C语言)

插入排序算法中的直接排序算法,折半插入排序算法,希尔排序算法。

 这三个算法理解顺序:直接----->折半-------->希尔排序算法。


#include
#include

#define N 10

typedef int KeyType;    //定义关键字类型
typedef int DataType;    //其他数据类型
typedef struct			//记录数据结构
{
	KeyType key;		//关键字
	DataType data;		//其他数据
}RecType;

/* InitRec : 创建排序的结构体数组 */
void InitRec(RecType arr_Rec[],int a[], int n)
{
	int i = 0;
	for (i = 0; i < n; ++i)
	{
		arr_Rec[i].key = a[i];   //排序的数据
		arr_Rec[i].data = 0;
	}
}

/* ShowData: 递归方式顺序打印排序结构体数组的关键字 */
void ShowData(RecType arr_Rec[], int n)
{
	if (n == 0) //到达末尾
	{
		printf("\n\n");
		return;
	}
	else
	{
		printf(" %-5d", arr_Rec[0].key);
		RecType *p;
		p = arr_Rec;
		p++;
		ShowData(p, n - 1);
	}
}

/*StraightInsertSort: 直接插入排序,将前面的元素设为有序区,后面的元素为无序区。一开始的时候有序区只有一个元素就是 R[0] */
void StraightInsertSort(RecType R[],int n)
{
	int i, j;
	KeyType temp;     //定义中间变量,用于临时存储
	int k=0;
	for (int i = 1; i < n; i++)  //因为第一个数不需要排序,所以从第二个开始循环
	{
		temp = R[i].key;     //存储当前要插入到有序区间的元素
		j = i - 1;
		while (j >= 0 && temp < R[j].key)  //将比temp大的数往后移一位,位插入做准备
		{
			k++;
			printf(" %d \n", k);     
			R[j + 1] = R[j];          
			j--;
		}
		R[j+1].key = temp;     //插入
		ShowData(R, n);
	}
}

/* BinaryInsertSort : 折半插入排序,折半查找算法对直接插入排序优化,将待插入到有序区的元素插入的时候利用折半查找找到插入的位置 */
void BinaryInsertSort(RecType R[], int n)
{
	int i, j, low, high, mid;
	RecType temp;  //准备存储中间变量
	for (i = 1; i < n; i++)
	{
		temp = R[i];     //将要插入的元素,这和直接插入排序是一样的
		j = i - 1;        
		low = 0;
		high = i - 1;
		while (low <= high)     //因为有序区已经有序,可以利用折半查找找到插入的位置
		{
			mid = (low + high) / 2;   
			if (temp.key < R[mid].key)      //说明temp(也就是R[i])的key值在R[low]到R[mid-1]之间
				high = mid - 1;
			else                    //说明temp(也就是R[i])的key值在R[mid+1]到R[high]之间
				low = mid + 1;
		}                             //当low>high时,找到了插入的位置就是high+1了
		for (j = i - 1; j >= high + 1; j--)
			R[j + 1] = R[j];
		R[high+1] = temp;
		ShowData(R, n);
	}
}

/* SellSort: 希尔排序算法 */
void ShellSort(RecType R[], int n)
{
	int i, j, gap;     //gap为增量
	RecType temp;       
	gap = n / 2;		//增量初值为总的一半
	while (gap > 0)
	{
		for (i = gap; i < n; i++)  //这是关键,其实就是对相隔gap的元素进行直接插入排序
		{
			temp = R[i];
			j = i - gap;
			while (j >= 0 && temp.key < R[j].key)  //这里明显就是直接插入排序,只是这里不是1而是gap
			{										//当gap=2的时候,就是直接插入排序
				R[j + gap] = R[j];
				j = j - gap;
			}
			R[j + gap] = temp;
		}
		gap = gap / 2;    
	}
}

int main()
{
	int a[N] = {4,2,6,9,5,7,1,3,8,10};
	//int a[N] = {10,9,8,7,6,5,4,3,2,1};
	//int a[N] = {1,2,3,4,5,6,7,8,9,10 };
	RecType arr_Rec[N];
	InitRec(arr_Rec, a, N);
	//printf("%d\n", arr_Rec[])
	ShowData(arr_Rec, N);
	//StraightInsertSort(arr_Rec, N);
	BinaryInsertSort(arr_Rec, N);
	ShowData(arr_Rec, N);

	system("pause");
	return 0;
}


你可能感兴趣的:(插入算法(C语言))