在一个从小到大排序的数组里插入一个数字
1.
#include <iostream>
using namespace std;
int main()
{
int a[6] = { 1,3,6,7,8 };
int x;
cout << "请输入需要插入的数字" << endl;
cin >> x;
int i = 0;
for (; i < 5; i++)
{
if (a[i] > x)//遍历数组,若数组元素比插入的数字大立马跳出循环
break;
}
for (int j = i; j <= 5; j++)
{
int y = a[j];//定义一个变量等于跳出的数组元素
a[j] = x;//插入数字
x = y;//再赋值原本的数字,循环排列完后面的数字
}
for (i = 0; i < 6; i++)
cout << a[i] << " ";
}
2.
#include <iostream>
using namespace std;
int main()
{
int a[6] = { 1,3,4,6,7 };//数组一
int x;
cout << "请输入需要插入的数字" << endl;
cin >> x;
int b[6];//新定义一个元素相同的数组,数组二
int i;
for (i = 0; i < 5; i++)//遍历数组
{
if (a[i] < x)//如果元素小于要插入的数字,就把数组一赋值给新定义的数组二
b[i] = a[i];
else break;//否则跳出循环
}b[i] = x;//插入数字
for (int j = i; j < 5; j++)//遍历数组,数组一剩下的元素赋给数组二
b[j + 1] = a[j];
for (i = 0; i < 6; i++)
cout << b[i] << " ";
}
3.
#include <iostream>
using namespace std;
int main()
{
int a[6] = { 1,3,4,6,7 };
int i;
int x;
cout << "请输入需要插入的数字" << endl;
cin >> x;
for (i = 4; i >= 0; i--)//从后向前推进
{
if (a[i] > x)
a[i + 1] = a[i];//一个个往后推顶后面的位置
else break;
}a[i+1] = x;//跳出后空位马上插入数字
for (i = 0; i < 6; i++)
cout << a[i] << " ";
}
[点击并拖拽以移动]