将随机数插入排序顺序为C++的数组中

Inserting a random number into an array with sorted order C++

本文关键字:数组 C++ 随机数 插入排序 顺序      更新时间:2023-10-16

你好,我正在尝试制作一个插入随机数的数组,但当它插入随机数时,数组会保持在一个保持的顺序中。例如,如果数组包含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