个人答案:
①
#include <iostream>
using namespace std;
int main()
{
int n[10] = { 12, 34, 56, 67, 78, 89, 90, 92, 95 };//设定一个排好序的数组
int num, i, j;
cout << "Please enter insert number: ";
cin >> num;//输入一个需要插入的数
for (i = 0; i < 9; i++)
{
if (num < n[i]) //如果这个要插入的数小于其中一个元素的话就插入其前
{
for (j = 9; j >= i; n[j] = n[j - 1], j--);//后退
n[i] = num;//然后将此数设置到n[i]前方
break;
}
//最后一种情况,如果插入的数大于n[8]元素那么最后一个元素n[9]便是这个数
else if (num > n[8])
{
n[9] = num;
break;
}
}
for (i = 0, cout << "New array: "; i < 10; cout << n[i++] << ' ');
//i实际为0-9,然后依次累加输出插入后数组即可
cout << endl;
system("pause");
return 0;
}
②
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
int i, j;
int a[10] = { 1,2,3,5,7,8,9,10 ,11 };
int m;
cout << "一个排好序的数组:";
for (i = 0; i < 9; i++)
cout << a[i] << " "; //输出数组的每个数。例如:a[0]=1,a[1]=2
cout << endl;
cout << "输入想要插入的数:";
cin >> m;
for (i = 0; i < 9; i++)
{
if (a[i] > m) //比较出数组中大于m的数
{
for (j = 8; j >= i; j--)
a[j + 1] = a[j]; //将a[]中每个大于m的数依次往后移一位
a[i] = m;
break; //插入完成跳出整个循环
}
else if (a[8] < m)
{
a[9] = m;
break;
}
}
cout << "插入之后:";
for (i = 0; i <= 9; i++)
{
cout << a[i] << " ";
}
cout << endl;
return 0;
}
结果(其一):
参考答案:
#include <iostream>
using namespace std;
int main()
{
int a[11]={1,4,6,9,13,16,19,28,40,100};
int num,i,j;
cout<<"array a:"<<endl;
for (i=0;i<10;i++)cout<<a[i]<<" ";
cout<<endl;;
cout<<"insert data:";
cin>>num;
if (num>a[9])
a[10]=num;
else
{for (i=0;i<10;i++)
{if (a[i]>num)
{for (j=9;j>=i;j--)
a[j+1]=a[j];
a[i]=num;
break;
}
}
}
cout<<"Now, array a:"<<endl;
for (i=0;i<11;i++)
cout<<a[i]<<" ";
cout<<endl;
return 0;
}