Kayla Bianchi
Kayla Bianchi

Reputation: 67

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

Hello I am trying to make an array that inserts a random number but when it does, the array stays in a maintained order. For example if the array contained 10 20 30 and the random number was 11 the function would put it after 10 and move 20 and 30 down the list. Here are the requirements for the function.

Here is my code so far. I am getting nothing in my output.

#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];
    }

}

Upvotes: 1

Views: 13569

Answers (4)

VThapa
VThapa

Reputation: 9

Insert your random number after you find the element greater than it, inside your function

for( i =0; i<size ;i++)
{
    if(data[i] > randomNumber)
    {
         valueToPush = data[i];
         data[i] = randomNumber;
         randomNumber = valueToPush;
    }
}
data[size] = randomNumber

Upvotes: -1

Thanatos
Thanatos

Reputation: 1186

You could use BinarySearch to search your array and see if the random number exists. If it does exist than you can insert near the existing one.

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
    }
}

Upvotes: 1

Rapptz
Rapptz

Reputation: 21317

Wouldn't this be a better way of implementing it?

#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 << " ";
}

Output: 3 6 9 13 14 16 19 20 25 30

Upvotes: 0

Benoit
Benoit

Reputation: 79243

You can use std::lower_bound algorithm to have an insertion position, and an std::vector container to shift the elements with the insert method

Upvotes: 4

Related Questions