⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 插入排序.cpp

📁 这里面包括数据结构多数的算法
💻 CPP
字号:
#include <stdio.h>
typedef int InfoType;

#define n 10					//假设的文件长度,即待排序的记录数目
typedef int KeyType;			//假设的关键字类型
typedef struct {				//记录类型
	KeyType key;				//关键字项
	InfoType otherinfo;			//其它数据项,类型InfoType依赖于具体应用而定义
} RecType;
typedef RecType SeqList[n+1];	//SeqList为顺序表类型,表中第0个单元一般用作哨兵

void main()
{
	void BInsertSort(SeqList R);
	int i;
	SeqList R;
	printf("请输入欲排序的数:");
	for (i=1;i<=n;i++)
		scanf("%d",&R[i].key);
	printf("排序前:");
	for (i=1;i<=n;i++)
		printf("%d ",R[i].key);
	printf("\n");
	BInsertSort(R);
	printf("排序后:");
	for (i=1;i<=n;i++)
		printf("%d ",R[i].key);
	printf("\n");
}

void BInsertSort(SeqList R)
{	//对顺序表R中的记录R[1..n]作二分插入排序
	int i,j,low,high,mid;
	for(i=2;i<=n;i++)
	{
		R[0]=R[i];					//将R[i]暂存到R[o]
		low=1;
		high=i-1;
		while(low<=high)			//在R[low..high]中折半查找有序插入的位置
		{
			mid=(low+high)/2;			//折半
			if (R[0].key<R[mid].key)
				high=mid-1;			//插入点在低半区
			else
				low=mid+1;			//插入点在高半区
		}
		for(j=i-1;j>=high+1;j--)
			R[j+1]=R[j];			//记录后移
		R[high+1]=R[0];				//插入
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -