Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting an element into an array

Tags:

c++

arrays

How can I make an inset method that will add a number into the array in the correct order?

void addElement(int table[], int element, int length) {
    int x = 0;
    int temporary=0;
    cout<<length<<endl;

    if(length == 1) {
        table[0] = element;
    }
    else {
        if(length == 2) {
            if (table[0] > element) {
               int temp = table[0];
               table[0] = element;
               table[1] = temp;
            }
            else {
                table[1] = element;
            }
        }
        else {
            for(int i = 0; i< length && x == 0; i++) {
                if(element<table[i] && element>=table[i-1]) {
                    for(int y = i; y<length; y++) {
                        temporary = table[y+2];
                        int temp = table[y];
                        table[y] = element;
                        table[y+1] = table
                     }
                }
            }
        }
    }
}

This is as far as I have gotten. In my main class I have worked it out so that array is increased by 1. So there is one open space at the end of the array for everything to be pushed back by 1.

like image 550
Bill Avatar asked Dec 06 '22 17:12

Bill


1 Answers

You can scan the array from back to front, moving values up until you find the correct insertion point.

void addElement(int *table, int element, int length)
{
    int i = length - 1;
    for (; i > 0 && table[i-1] > element; --i)
    {
        table[i] = table[i-1];
    }
    table[i] = element;
}
like image 195
Blastfurnace Avatar answered Dec 21 '22 23:12

Blastfurnace