插入排序数组 [英] insert into sorted array

查看:113
本文介绍了插入排序数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将元素插入顺序在已排序列表中维护的正确位置。
我为数组分配了2 * n的大小,其余部分用999填充,因为它们当前未被使用。

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;

}

我不知道如何覆盖999,或者还有更好的方法吗?

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

推荐答案

为了将所有后面的数组元素向前移动,您必须遍历向后排列数组,以免覆盖元素。

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.

获得索引后,

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

这篇关于插入排序数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆