题目链接:点击打开链接
数列有序!
Time Limit: 1000ms Memory limit: 65536K 有疑问?点这里^_^
题目描述
有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数m,请将该数插入到序列中,并使新的序列仍然有序。
输入
输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0表示输入数据的结束,本行不做处理。
输出
对于每个测试实例,输出插入新的元素后的数列。
示例输入
3 3 1 2 4 0 0
示例输出
1 2 3 4
提示
代码实现:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
#define maxsize 110
typedef struct
{
int *elem;
int length;
int lastsize;
}Sq;
///建立空表
int initList(Sq *L)
{
L->elem=(int *)malloc(maxsize*sizeof(int));
if(!L->elem) return -1;
L->length=0;
L->lastsize=maxsize;
return 0;
}
void create(Sq *L,int n)
{
for(int i=0;i<n;i++)
scanf("%d",&L->elem[i]);
L->length=n;
}
///进行插入操作
void Insert(Sq *L,int n)
{
int i;
for(i=0;i<L->length;i++)
{
if(L->elem[i]>n)///找比插入元素大的
{
for(int j=L->length-1;j>=i;j--)
{
L->elem[j+1]=L->elem[j];///实现后移
}
L->elem[i]=n;
L->length++;
break;
}
}
///
if(i>L->length-1)
{
L->length++;
L->elem[L->length-1]=n;
}
}
void display(Sq *L)
{
for(int i=0;i<L->length-1;i++)
printf("%d ",L->elem[i]);
printf("%d\n",L->elem[L->length-1]);
}
int main()
{
Sq L;
int n,m;
while(~scanf("%d%d",&n,&m)&&(n||m))
{
initList(&L);
create(&L,n);
Insert(&L,m);
display(&L);
}
return 0;
}