插入已排序的数组

我想在正确的位置插入一个元素,该顺序在排序列表中维护。 我为arrays分配了2 * n的大小,并用999填充其余的,因为它们目前没有使用。

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; } 

我无法弄清楚如何覆盖999s或者有更好的方法吗?

为了将所有后面的数组元素向前移动一步,您必须向后遍历数组,这样就不会覆盖元素。

一旦获得索引,

 int i = size; while ( i > index ) { array[i] = array[i-1]; i--; } array[i] = number; size++; 

您可以

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

编辑:

不需要999技巧; 只记录size中使用过的元素的size (并添加适当的边界检查)。

要推送数组元素的其余部分,您应该使用循环。 只是做车,你应该从最后一个元素开始推动,否则你将为其余元素分配相同的值

 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; 

关于使用999分配未使用的元素,不需要仅定义一个键来记住最后一个元素并使用它而不是大小,然后在插入新元素时检查是否达到了数组的大小。

 // 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;