有一系列数字,可能是按正序排列也有可能是按照倒序排列,现在用户给出一个值,能按照原本顺序插入到正确的位置,并打印出来!!
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
int main()
{
srand((unsigned)time(NULL)); // 初始化随机数生成器
int oldOrder[10]{}; // 初始排名
for (int& x : oldOrder)
x = rand() % 501;
int dir = rand() % 2;
switch (dir)
{
case 0:
std::sort(oldOrder, oldOrder + 10,std::greater<int>());
break;
case 1:
std::sort(oldOrder, oldOrder + 10);
}
std::cout << "初始数据排名:" << std::endl;
for (int x : oldOrder)
std::cout << x << "\t";
std::cout << std::endl;
int input{};
std::cout << "请输入一个值:";
std::cin >> input;
int flag{};
if (oldOrder[0] > oldOrder[9]) // 逆序
flag = 0;
else
flag = 1;
int* newOrder = new int[10] {0};
switch (int index{ 0 }; flag) // C++17之后新特性
{
case 0: //逆序
while (index < 10)
{
if (oldOrder[index] > input)
{
newOrder[index] = oldOrder[index];
index++;
}
else
{
newOrder[index] = input;
break;
}
}
while (index < 10)
{
newOrder[index + 1] = oldOrder[index];
index++;
}
break;
case 1:
while (index < 10)
{
if (oldOrder[index] < input)
{
newOrder[index] = oldOrder[index];
index++;
}
else
{
newOrder[index] = input;
break;
}
}
while (index < 10)
{
newOrder[index + 1] = oldOrder[index];
index++;
}
}
std::cout << "插入 " << input << " 之后的数据为:" << std::endl;
for (int i = 0; i < 11; i++)
std::cout << newOrder[i] << "\t";
std::cout << std::endl;
}
结果1
初始数据排名:
104 112 152 167 333 418 418 448 460 484
请输入一个值:150
插入 150 之后的数据为:
104 112 150 152 167 333 418 418 448 460 484
结果2
初始数据排名:
480 423 419 387 298 268 192 91 73 15
请输入一个值:
490
插入 490 之后的数据为:
490 480 423 419 387 298 268 192 91 73 15
#include <iostream>
#include <cstdlib>
#include <ctime>
#include <algorithm>
int main()
{
srand((unsigned)time(NULL)); // 初始化随机数生成器
int oldOrder[10]{}; // 初始排名
for (int& x : oldOrder)
x = rand() % 501;
int dir = rand() % 2;
switch (dir)
{
case 0:
std::sort(oldOrder, oldOrder + 10,std::greater<int>());
break;
case 1:
std::sort(oldOrder, oldOrder + 10);
}
std::cout << "初始数据排名:" << std::endl;
for (int x : oldOrder)
std::cout << x << "\t";
std::cout << std::endl;
int input{};
std::cout << "请输入一个值:";
std::cin >> input;
int* newOrder = new int[11] {0};
int inputLocal{ 10 };
for (int i = 0; i < 10; i++)
{
if ((oldOrder[0] > oldOrder[1]) ^ (input < oldOrder[i]))
{
inputLocal = i;
break;
}
}
memcpy(newOrder, oldOrder, inputLocal * 4);
memcpy(newOrder + inputLocal + 1, oldOrder + inputLocal, (10 - inputLocal) * 4);
newOrder[inputLocal] = input;
std::cout << "插入 " << input << " 之后的排序:" << std::endl;
for (int i = 0; i < 11; i++)
std::cout << newOrder[i] << "\t";
std::cout << std::endl;
}
结果1
初始数据排名:
86 92 97 121 208 245 286 312 348 395
请输入一个值:11
插入 11 之后的排序:
11 86 92 97 121 208 245 286 312 348 395
结果2
初始数据排名:
433 364 344 317 234 233 219 161 59 10
请输入一个值:0
插入 0 之后的排序:
433 364 344 317 234 233 219 161 59 10 0