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

已知数列插入数字排序。

#include <stdio.h>

int main(void)
{
    
    
	int i, j, n, x;
	int arr[101];

	printf("Input:\n");
	scanf("%d%d", &n, &x);
	while (n != 0 || x != 0)
	{
    
    
		for (i = 0; i < n; i++)//用到了while——为了判定n和x是否为0和for的循环嵌套,最开始这一点并不容易想到
		{
    
    
			scanf("%d", &arr[i]);
		}

		for (j = n - 1; j >= 0 && x < arr[j]; j--)//从最后个数比较,之后遇到大的向前移动一位
		{
    
    
			arr[j + 1] = arr[j];//交换位置
		}
		arr[j + 1] = x;//之后x>arr[j],x赋值给arr[j+1].一到达插入的数字进行排序
		printf("Output: ");
		for (i = 0; i <= n; i++)
		{
    
    
			printf("%d ", arr[i]);
		}
		printf("\n");

		scanf("%d%d", &n, &x);//while循环中再次输入.
	}
	return 0;
}

分析在代码中…

猜你喜欢

转载自blog.csdn.net/yooppa/article/details/114939807