作业:简化的插入排序



本题要求编写程序,将一个给定的整数插到原本有序的整数序列中,使结果序列仍然有序。

输入格式:

输入在第一行先给出非负整数N(<10);第二行给出N个从小到大排好顺序的整数;第三行给出一个整数X。

输出格式:

在一行内输出将X插入后仍然从小到大有序的整数序列,每个数字后面有一个空格。

输入样例:

5
1 2 4 5 7
3

输出样例:

1 2 3 4 5 7
#include <iostream>
#include <cmath>
#include <stdio.h>
#include <string>

using namespace std;
int main() {
 int x,a[11],t=0;
 unsigned int n;//要求是非负数 
 cin >> n;
 for (int i = 0; i < n; i++) {
   cin >> a[i];
  } 
  cin >> x;
 
  for (int i = 0; i < n; i++) {
   if (x < a[i]) {
    for (int j = n; j >= i; j--)
    {
     a[j + 1] = a[j];
     t++;
    }
    a[i] = x;
    break;
   }
 
  }
  if (t == 0)
   a[n] = x;//x都比前面的大 不加这个放在尾部是错误的 
  for (int i = 0; i <= n; i++) {
    cout << a[i] << " ";
   }
 
  cout << endl;
 
 
 return 0;
} //新手 

猜你喜欢

转载自blog.csdn.net/Yuoliku/article/details/78744648