0

I'm trying to make this program which gets an element from user and inserts it into the made array by user (array must be sorted) But it doesn't work properly

for example: a[4]

a[0]=1
a[1]=3
a[2]=5
a[3]=7

then i insert>> 6

but then it goes like this

a[0]=1
a[1]=3
a[2]=5
a[3]=6
a[4]=3866936

the array is able to have upto 100 elements

:|

it's a practice from a book

#include<iostream>
#include<windows.h>
using namespace std;

void insert(int[], int&, int);

int main()
{
    const int maxsize = 100;
    int a[maxsize];
    cout << "build ur array\n";  Sleep(650);
    cout << "Enter the number of elements:";
    int n;
    cin >> n;

    for (int i = 0; i < n; i++)
    {
        cout << "a[" << i << "]=";
        cin >> a[i];
    }
    int k;
    cout << "Enter a new element:";
    cin >> k;
    n++;
    insert(a, n, k);
    for (int i = 0; i < n; i++)
        cout << "a[" << i << "]=" << a[i] << endl;
    system("pause");
 }



void insert(int a[], int& n, int x)
{
    for (int i = n - 1; a[i]>x; i--)
        a[i] = a[i + 1];
     for (int i = n; i <= n; i--)
     {
         if (x >= a[i])
         {
             a[i + 1] = x;
             break;
         }
     }
5
  • 2
    If the array has only 4 elements you cannot make it have 5 elements. The C++ way of doing it is to use std::vector<int> v; v.push_back(6); and let the standard library worry about annoying pointer fiddling. Commented Aug 11, 2014 at 12:49
  • you are saying 4 elements, but the code shows you have an array of 100. int a[maxsize]; Commented Aug 11, 2014 at 12:51
  • You'll have problems with inserting a number smaller than those already in the array, and you don't need the second loop in insert (the location you want is where the first loop stopped - you don't need to search again). Commented Aug 11, 2014 at 13:53
  • @lakesh that's not the problem Commented Aug 11, 2014 at 14:36
  • @nwp but the array can have upto 100 elements Commented Aug 11, 2014 at 14:39

5 Answers 5

3

Assuming you know what you're doing ex. no one can enter more than 99, assuming you will check if the value is less than 100, you have only one error in insert:

a[i] = a[i+1];

should be

a[i+1] = a[i];

The full function should look like this to work with all possible cases:

void insert(int a[], int& n, int x)
{
    for (int i = n - 2; a[i]>x && i >= 0; i--)
        a[i+1] = a[i];
    for (int i = n-2; i >= 0; i--)
    {
        if (x >= a[i])
        {
            a[i + 1] = x;
            return;
        }
    }
    a[0] = x;
}
Sign up to request clarification or add additional context in comments.

2 Comments

+1. (It seems you're the only one who read the code and answered the actual question rather than just repeating the "use std::vector" mantra.)
im not sure but i think they are same my edit works in any case too but im not sure tnx
2

You are experiencing undefined behavior due to the fact that you are reading from outside of the array bounds (0 - 3). You should use an std::vector for dynamically sized arrays:

std::vector<int> vec;
vec.push_back(1);
vec.push_back(3);
vec.push_back(5);
vec.push_back(7);

and then:

vec.push_back(6);

Later on, if you want to sort the array you can just do:

std::sort(vec.begin(), vec.end());

2 Comments

Or if he doesn't have knowledge or experience with vectors, I'd recommend just making a grow() function. Clearly vectors are the way to go though.
@WhyCry You think learning how to write a correct grow() function is easier that learning to use std::vector?
0

You just need to remember that index of array starts from 0. When you want to have 4 elements array int tab[4] you can can read/write elements value using indexes from 0 to 3 tab[0], tab[1], tab[2], tab[3]. Element tab[4] is not part of your array and when you want to read element from your such place, you will get value that is already there (you can think about it as unpredictable random value, but it is not true random value).

By the way, you question is about C language. If you using C++, read about containers like std::array, std::vector etc.

Comments

0

With some stuff from STL, you may use the following:

class SortedVector
{
public:
    using const_iterator = std::vector<int>::const_iterator;

    void insert(int value) {
        auto it = std::lower_bound(v.begin(), v.end(), value);
        v.insert(it, value);
    }

    const_iterator begin() const { return v.begin(); }
    const_iterator end() const { return v.end(); }

private:
    std::vector<int> v;
};

Live Example

  • std::vector is the container.
  • std::lower_bound finds the location where to insert (the way that insertion is still in order)
  • std::vector::insert does the insertion (which the shifting of the element).

if you don't want to use std::vector and us C-array: you may use:

void insert(int a[], int& n, int x)
{
    auto it = std::lower_bound(a, a + n, x);
    std::copy(it, a + n, it + 1);
    *it = x;
    ++n;
}

Live example.

Comments

0

> with help of prajmus i solved the problem :

#include<iostream>
#include<windows.h>
using namespace std;

void insert(int[], int&, int);

int main()
{
const int maxsize = 100;
int a[maxsize];
cout << "build ur array\n";  Sleep(650);
cout << "Enter the number of elements:";
int n;
cin >> n;

for (int i = 0; i < n; i++)
{
    cout << "a[" << i << "]=";
    cin >> a[i];
}
int k;
cout << "Enter a new element:";
cin >> k;
n++;
insert(a, n, k);
for (int i = 0; i < n; i++)
    cout << "a[" << i << "]=" << a[i] << endl;
system("pause");
}



void insert(int a[], int& n, int x)
 {
 for (int i = n - 2; a[i]>x; i--)
    a[i+1] = a[i];

for (int i = n-1; i <= n; i--)
{
    if (x >= a[i])
    {   a[i + 1] = x;
        break;
}
}
 }

4 Comments

Actually it does not work if the element is less than the first or bigger than the last one, check my edit
well the array most be sorted from small to bigger
I know, but imagine you have [2,3,4,5] and insert [0] or [6], it won't work then.
it actually works in most of case even not sorted but ur edit is surely better

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.