7.1直接插入排序

#include "stdio.h"
#include "stdlib.h"
#define OK 		1
#define ERROR 	0
#define MAXSIZE 20

typedef int Status;
typedef int KeyType;

typedef struct {
	KeyType key;	//关键字
} ElemType;

typedef struct {
	ElemType r[MAXSIZE+1];	//r[0]闲置 or 哨兵,或缓冲区
	int length;
} SqList;

Status InitList(SqList &L,int n) {
	int i,num;
	L.length = 0;
	for(i=0; i<n; i++) {
		scanf("%d",&num);
		L.r[i].key = num;
		L.length++;
	}
	return OK;
}

//直接插入排序
Status InsertSort(SqList &L) {
	int i,j,temp;
	for(i=1; i<L.length; ++i)
	{
		if(L.r[i].key < L.r[i-1].key) 
		{
			temp = L.r[i].key;	//复制为哨兵
		    L.r[i].key = L.r[i-1].key;
			
			for(j=i-1; j>=0 && temp < L.r[j].key; --j)
			{
				L.r[j+1].key = L.r[j].key;
			}
			L.r[j+1].key = temp;
		}
	}
}

Status ListPrint(SqList L) {
	int i;
	for(i=0; i<L.length; i++)
		printf("%d ",L.r[i].key);
	return OK;
}

int main(void) {
	SqList L;
	int n;
	printf("请输入关键字序列个数:");
	scanf("%d",&n);
	printf("请输入%d个关键字:",n);
	InitList(L,n);
	InsertSort(L);
	printf("直接插入排序结果为:");
	ListPrint(L);
	return 0;
}

/*
测试输入:
5
12 33 15 10 8
预期输出:
8 10 12 15 33

测试输入:
10
49 33 15 10 8 77 49 78 88 16
预期输出:
8 10 15 16 33 49 49 77 78 88

测试输入:
8
1 2 3 4 5 6 7 8 9
预期输出:
1 2 3 4 5 6 7 8 9
*/
//3 5 4 6 9 7 8 1 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值