将随机数插入排序顺序为C++的数组中
Inserting a random number into an array with sorted order C++
你好,我正在尝试制作一个插入随机数的数组,但当它插入随机数时,数组会保持在一个保持的顺序中。例如,如果数组包含10 20 30,并且随机数为11,则函数会将其放在10之后,并将20和30从列表中下移。以下是该功能的要求。
- insertNumber将给定的随机数插入到数组中并保持顺序
- 数据数组包含按索引0到大小-2排序的整数
- randomNum是要插入的整数
- data是包含排序整数的数组
- size是数组可以容纳的元素总数
这是我迄今为止的代码。我的输出没有任何结果。
#include"utils.h"
void insertNumber(int randomNum, int data[], int size)
{
for(int i = 0; i < 10; i++)
{
randomNum = data[i];
if (randomNum > data[i] && i < size - 2)
{
for ( int j = 0; j < 10; j--)
{
data[i+1] = data [i];
i--;
}
}
data[i] = randomNum;
}
}
void display(int data[], int size)
{
for (int i = 0; size < 10; i++)
{
cout << " " << data[i];
}
}
您可以使用std::lower_bound
算法来获得插入位置,并使用std::vector
容器来使用insert
方法移动元素
您可以使用BinarySearch来搜索您的数组,并查看随机数是否存在。如果它确实存在,则可以在现有的附近插入。
void binary_search(int A[], int key, int imin, int imax)
{
if (imax < imin):
// Insert key as the next element after imax
else
{
// calculate midpoint to cut set in half
int imid = midpoint(imin, imax);
// three-way comparison
if (A[imid] > key)
// key is in lower subset
binary_search(A, key, imin, imid-1);
else if (A[imid] < key)
// key is in upper subset
binary_search(A, key, imid+1, imax);
else
// key has been found so insert it after imax
}
}
- 代码取自维基百科http://en.wikipedia.org/wiki/Binary_search_algorithm*
这不是更好的实现方式吗?
#include <iostream>
#include <vector>
#include <algorithm>
#include <ctime>
#include <cstdlib>
int main() {
std::vector<int> randomInts;
srand(time(0));
for(int i = 0; i < 10; i++)
randomInts.push_back((rand()%30)+1); //Inserts random numbers 1-30.
std::sort(randomInts.begin(),randomInts.end());
for(auto i : randomInts)
std::cout << i << " ";
}
输出:3 6 9 13 14 16 19 20 25 30
在函数中找到大于它的元素后,插入随机数
for( i =0; i<size ;i++)
{
if(data[i] > randomNumber)
{
valueToPush = data[i];
data[i] = randomNumber;
randomNumber = valueToPush;
}
}
data[size] = randomNumber
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 将数组的地址分配给变量并删除
- 从C++本机插件更新Vector3数组
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 数组索引的值没有增加
- 将对象数组的引用传递给函数
- 为char数组调整zlib-zpipe
- 2D数组来自文本输入,中间有空格
- std::向量与传递值的动态数组
- 在c++中用vector填充一个简单的动态数组
- 使用strcpy将char数组的元素复制到另一个数组
- 使用指针从C++中的数组中获取最大值
- C++使用整数的压缩数组初始化对象
- 告诉一个 const char 数组,除了编译时 C 样式的字符串外,它不以 '