我想将一个元素插入到排序列表中order维护的正确位置。我为数组分配了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,或者有没有更好的方法呢?
发布于 2013-11-27 00:46:37
你可以的
memmove(&array[i+1], &array[i], (size - i) * sizeof array[i]);编辑:
不需要999技巧;只需在size中记录使用的元素数量(并添加适当的边界检查)。
发布于 2013-11-27 00:54:23
为了将后面的所有数组元素向前移动一步,必须向后遍历数组,这样才不会覆盖这些元素。
一旦你得到了索引,
int i = size;
while ( i > index ) {
array[i] = array[i-1];
i--;
}
array[i] = number;
size++;发布于 2015-07-09 19:56:57
// 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; https://stackoverflow.com/questions/20222891
复制相似问题