杭电oj2019:数列有序!

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_38250032/article/details/81663204

杭电oj2019:数列有序!

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)
 

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=2019

Problem Description

有n(n<=100)个整数,已经按照从小到大顺序排列好,现在另外给一个整数x,请将该数插入到序列中,并使新的序列仍然有序。

Input

输入数据包含多个测试实例,每组数据由两行组成,第一行是n和m,第二行是已经有序的n个数的数列。n和m同时为0标示输入数据的结束,本行不做处理。

Output

对于每个测试实例,输出插入新的元素后的数列。

Sample Input

3 3

1 2 4

0 0

Sample Output

1 2 3 4

题目分析:简单的排序

代码示例:

1、类似于冒泡排序

#include<stdio.h>
#include<string.h>
const int MAX = 100;

int main()
{
	int num[MAX];
	int i, j,n, x,temp;
	while (scanf("%d %d", &n, &x),x||n)
	{
		for (i = 0; i < n; i++)
		{
			scanf("%d", &num[i]);
		}
		num[n] = x;
		for (j = n; j > 0; j--)
		{
			if (num[j] <= num[j - 1])
			{
				temp = num[j];
				num[j] = num[j - 1];
				num[j - 1] = temp;
			}
			else
				break;
		}
		for (i = 0; i < n; i++)
		{
			printf("%d ",num[i]);
		}	
		printf("%d\n",num[i]);
	}
	return 0;
}

2、用折半查找

#include<stdio.h>
#include<string.h>
const int MAX = 100;

int main()
{
	int num[MAX];
	int i, j, n, x, right,left;
	while (scanf("%d %d", &n, &x), x || n)
	{
		for (i = 0; i < n; i++)
		{
			scanf("%d", &num[i]);
		}
		right = n - 1;
		left = 0;
		while (left < right)
		{
			if (num[(left + right) / 2] == x)
				break;
			else if (num[(left + right) / 2]>x)
				right = (left + right) / 2 - 1;
			else
				left = (left + right) / 2 + 1;
		}
		for (i = n; i > (left + right) / 2; i--)
			num[i] = num[i - 1];
		num[(left + right) / 2] = x;
		for (i = 0; i < n; i++)
		{
			printf("%d ", num[i]);
		}
		printf("%d\n", num[i]);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_38250032/article/details/81663204