Click here to Skip to main content
15,442,007 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Algorithm to insert a value M at location Pos in an array ABC having N elements

1. input value in M.
2. Input position in Pos
[move elements one step forward]
3.Repeat step-4to 5 while N>=POS

4. ABC[N+1]=ABC[N]


[insert value M at position Pos]


I simply want to ask what happen if my array size is ABC[5]and index is from 0 to n-1 and i want to insert value at index 4 then what happen how this algorithm work?

and if i insert value at index 3 then how this algorithm work?

is the size of array incearse automatically
Updated 26-Jan-12 3:30am

It depends on the array type. If this is a simple C-type array then your code will fail. For dynamic expansion you should use the STL array[^] class.
Share this answer
Espen Harlinn 26-Jan-12 8:49am    
ALIWAZ 26-Jan-12 8:59am    
if i enter value at index 3 then that algorithm is valid or not
Richard MacCutchan 26-Jan-12 9:58am     CRLF
Yes the algorithm is valid (assuming you add code to expand the array), but why not just use one of the other STL collection classes (vector or list for instance) and let it do the work for you.
if my array size is ABC[4] and i want to insert value at index 4
Your program might crash as index 4 is just beyond the end of the array.

Best regards
Espen Harlinn
Share this answer
The provided algorithm works (on a statically allocated array) only if the allocated memory for the array is bigger than its current (logical) size.
int a[20];
int size = 0;
// fill the array
a[0] = 5; size++;
a[1] = 7; size++;
a[2] = 2; size++;
// now (logical) size = 3, while memory is allocated for 20 positions,
// that is you have 17 'spare' positions.

intert(1,4); size++; // insert 4 at position 1 (that is correct).
                     // note the logical size must be increased.

If you allocate dynamically the array (using, for instance, malloc[^] function) then you may use, when needed, the realloc[^] function to increase the buffer.

Please note:
  • The above argument is independent on the insertion position (provided you insert within the boundaries or append the item). It depends only on logical size vs physical allocated memory.
  • C++ provides containers classes (like for instance std::vector[^]) that handle automatically memory allocation for you. For instance:
    #include <vector>
    #include <iostream>
    using namespace std;
    int main()
      vector <int> v;
      vector<int>::iterator it = v.begin() + 1;
      v.insert(it, 4); // insert the element, no need to manage array's growth
      cout << v[1] << endl;
Share this answer
Espen Harlinn 26-Jan-12 9:47am    
Excellent reply - my 5!
CPallini 27-Jan-12 3:02am    
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900