C++向数组内插入一个数并进行排序
问题:C++向数组内插入一个数并进行排序
本程序已经经过VC++ 6.0编译运行,具体为,一个数组已经按照从小到大的顺序排好,现在从键盘输入一个数,要求将数组依旧按照从小到大的顺序进行排序:
#include <iostream>
using namespace std;
int main()
{
int a[11] = { 1, 2, 13, 17, 28, 40, 56, 78, 89, 100 };
int num, i, j;
cout << "now the array is:" << endl;
for (i = 0; i<10; i++)
{
cout << a[i] << " ";
}
cout << endl << "now the array is:" << endl;
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 the array is:" << endl;
for (i = 0; i<11; i++)
{
cout << a[i] << " ";
}
cout << endl;
system("pause");
return 0;
}
程序运行结果: