Inserting into array in order

crackhamster picture crackhamster · Dec 3, 2013 · Viewed 9.3k times · Source

In simple terms, part of the project I'm working on has me taking an array that is descending in order and adding an element so that it the array remains in order. Initially I thought it would be simple just to add the element into the array and then sort after implementing Comparable, but then found out that sorting algorithms of any kind are prohibited; Collections as well. Kind of out of ideas on how to proceed from here, any hints?

EX:

int[] x = [ 7, 6, 6, 5, 3, 2, 1 ] 

add 4

[ 7, 6, 6, 5, 4, 3, 2, 1 ]

Clarification to say that I am not completely out of ideas, just efficient ones. What I am able to reason so far:

int[] bigger = new int[x.length];
int add = 4;
for (int i = 0; i < bigger.length; i++){
     if ( add > x[i] && add < x[i+1]){
         bigger[i] = x[i];
         bigger[i+1] = add;
     else{
         bigger[i] = x[i];
     }
}

I know it will throw an IndexOutOfBounds error for x, but I feel there must be a simpler method than this, right?

Answer

Sureshkumar Panneerselvan picture Sureshkumar Panneerselvan · Dec 3, 2013

Once you find the right place i.e. if(value < list[i]){ is true then move all available elements to right. You are moving only one by using list[i+1]= list[i];

   list[numElements] = value;
    for(int i = 0; i < numElements; i++){
        //May be I should use a nested loop?
        //for(k = 0; k <)
         if(value < list[i]){
             for(int j= numElements-1; j>=i; j--){
                  list[j+1]= list[j];
              }
              list[i] = value;
              break;
        }
    }
    numElements++;