首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >插入到排序数组中

插入到排序数组中
EN

Stack Overflow用户
提问于 2013-11-27 00:42:36
回答 5查看 12.9K关注 0票数 0

我想将一个元素插入到排序列表中order维护的正确位置。我为数组分配了2*n大小,并用999填充了剩余的数组,因为它们当前并不使用。

代码语言:javascript
运行
复制
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,或者有没有更好的方法呢?

EN

回答 5

Stack Overflow用户

发布于 2013-11-27 00:46:37

你可以的

代码语言:javascript
运行
复制
memmove(&array[i+1], &array[i], (size - i) * sizeof array[i]);

编辑:

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

票数 2
EN

Stack Overflow用户

发布于 2013-11-27 00:54:23

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

一旦你得到了索引,

代码语言:javascript
运行
复制
int i = size;
while ( i > index ) {
  array[i] = array[i-1];
  i--;
}
array[i] = number;
size++;
票数 2
EN

Stack Overflow用户

发布于 2015-07-09 19:56:57

代码语言:javascript
运行
复制
// 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;                            
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/20222891

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档