习题 5.4 有一个已排好序的数组,今输入一个数,要求按原来排序的规律将它插入数组中。
代码:
#include <iostream>
#include<iomanip>
using namespace std;
int main()
{
int a[6] = { 1,9,13,40,100 };
int num, i, j;
cout << "原数组:" << endl;
for (i = 0; i < 5; i++)
cout <<setw(4)<< a[i] ;
cout << endl;
cout << "请输入插入值:";
cin >> num;
if (num > a[4])
a[5] = num;
else
{
for (i = 0; i < 5; i++)
{
if (a[i] > num)
{
for (j = 4; j >= i; j--)
a[j + 1] = a[j];
a[i] = num;
break;
}
}
}
cout << "新数组为:" << endl;
for (i = 0; i < 6; i++)
cout << a[i] << " ";
cout << endl;
return 0;
}