方案一(有优化空间):
int Index{};
int num{};
//int a[10]{ 105,98,73,58,32,31,25,22,3,1 };
int a[10]{ 1,3,22,25,31,32,58,73,98,105 };
int acount = sizeof(a) / sizeof(int);
std::cout << "请输入需要写入的数字:" << std::endl;
std::cin >> num;
if (a[0] > a[9])
{
for (int x = 0; x < 10; x++)
{
if (a[x] <= num)
{
//std::cout << x << std::endl;
Index = x;
break;
}
}
}
else
{
for (int x = 0; x < 10; x++)
{
if (a[x] >= num)
{
//std::cout << x << std::endl;
Index = x;
break;
}
}
}
int* p = new int[acount + 1];//堆区开辟的空间,不是连续的
memcpy(p, a, Index * sizeof(int));
memcpy(p + Index + 1, a + Index, (acount - Index) * sizeof(int));
p[Index] = num;
for (int x = 0; x < acount + 1; x++)
{
std::cout << p[x] << std::endl;
}
方案二(优化后):
//PS:一正一反的条件,可以简化如下:
//异或:不同为1,相同为0
int Index{};
int num{};
//int a[10]{ 105,98,73,58,32,31,25,22,3,1 };
int a[10]{ 1,3,22,25,31,32,58,73,98,105 };
int acount = sizeof(a) / sizeof(int);
std::cout << "请输入需要写入的数字:" << std::endl;
std::cin >> num;
//PS:一正一反的条件,可以简化如下:
//异或:不同为1,相同为0
/*
for (int x = 0; x < 10; x++)
{
***********改写成异或****************
if (a[0] > a[9])//正
{
if (a[x] <= num)//正
{
//std::cout << x << std::endl;
Index = x;
break;
}
}
if(a[0] < a[9])//反
{
if (a[x] >= num)//反
{
//std::cout << x << std::endl;
Index = x;
break;
}
}
**********改写成异或*****************
}
*/
/********** 改写成异或*****************/
bool bcase = a[0] > a[9];
for (int x = 0; x < 10; x++)
{
if (bcase ^ (a[x] >= num))
{
//std::cout << x << std::endl;
Index = x;
break;
}
}
int* p = new int[acount + 1];//堆区开辟的空间,不是连续的
memcpy(p, a, Index * sizeof(int));
memcpy(p + Index + 1, a + Index, (acount - Index) * sizeof(int));
p[Index] = num;
system("cls");
std::cout << "杀手排名:" << std::endl;
for (int x = 0; x < acount + 1; x++)
{
std::cout << p[x] << " ";
}
std::cout << std::endl;