insert into sorted array

2019-08-29 16:13发布

I want to insert an element into the right place that order maintains in the sorted list. I allocated 2*n size for the array and filled the rest with 999 since they are not used currently.

ordered_insert(int number,int array[],int size){
 int i=0;
 int temp1,temp2,index;
 while(eleman>array[i]){
   i++;}

//push the rest to right by one
index=i;

if(i<size){
    temp1=array[i];
    temp2= array[i+1];
    array[i+1]=temp1;
    array[i+2]=temp2;
    i++;
    }

array[index]=number;

}

I couldn't figure out how to overwrite 999s or is there a better way instead?

4条回答
forever°为你锁心
2楼-- · 2019-08-29 16:46

you can

memmove(&array[i+1], &array[i], (size - i) * sizeof array[i]);

EDIT:

The 999 trick is not needed; just record the number of used elements in size (and add appropriate boundary checks).

查看更多
叛逆
3楼-- · 2019-08-29 17:05

In order to move all the latter array elements one step ahead, you will have to traverse the array backwards so that you do not over-write the elements.

Once you get the index,

int i = size;
while ( i > index ) {
  array[i] = array[i-1];
  i--;
}
array[i] = number;
size++;
查看更多
Evening l夕情丶
4楼-- · 2019-08-29 17:08
// 1. initialise i (the 'hole' index) to the last element in the array
// 2. if the preceeding array element is larger than the newValue
// 3.   move the preceeding element into the 'hole' at i, moving the hole up a position
// 4.   reverse through the array
// 5. else put the newValue into the hole and we're done 

i = ARRAY_SIZE-1;  
while (i>0 && array[i-1]>newValue) {
  array[i] = array[i-1];
  i--;
}
array[i] = newValue;                            
查看更多
Animai°情兽
5楼-- · 2019-08-29 17:10

To push the rest of the array element's you should use a loop. Just be carfare you should start pushing from the last element otherwise you will assign the rest of elements with the same value

int i=size-1; // Not i=size (this is the size of the array not the last index)
while (i>index){
array[i] = array[i-1];
i--;
}
array[i] = number;

about assigning the unused elements with 999 it's not required just define a key to remember the last element and use it instead of size, then when inserting a new element just check if you reached the size of the array.

查看更多
登录 后发表回答