我想将一个元素插入到排序列表中顺序保持的正确位置。
我为数组分配了 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;
}
我不知道如何覆盖 999 或者有更好的方法吗?
为了将后面的所有数组元素向前移动一步,您必须向后遍历数组,以免覆盖元素。
获得索引后,
int i = size;
while ( i > index ) {
array[i] = array[i-1];
i--;
}
array[i] = number;
size++;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)