按顺序插入数组 [英] Inserting into array in order

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

问题描述

简单来说,我正在处理的项目的一部分是让我按顺序递减的数组并添加一个元素,以使该数组保持顺序.最初,我认为将元素添加到数组中,然后在实现Comparable之后进行排序会很简单,但是后来发现禁止使用任何类型的排序算法.以及收藏.有点关于如何从这里开始的想法,有什么暗示吗?

In simple terms, part of the project I'm working on has me taking an array that is descending in order and adding an element so that it the array remains in order. Initially I thought it would be simple just to add the element into the array and then sort after implementing Comparable, but then found out that sorting algorithms of any kind are prohibited; Collections as well. Kind of out of ideas on how to proceed from here, any hints?

EX:

int[] x = [ 7, 6, 6, 5, 3, 2, 1 ] 

add 4

[ 7, 6, 6, 5, 4, 3, 2, 1 ]

澄清一下,我并不是完全没有想法,只是有效率的想法.到目前为止,我能得出的结论是

Clarification to say that I am not completely out of ideas, just efficient ones. What I am able to reason so far:

int[] bigger = new int[x.length];
int add = 4;
for (int i = 0; i < bigger.length; i++){
     if ( add > x[i] && add < x[i+1]){
         bigger[i] = x[i];
         bigger[i+1] = add;
     else{
         bigger[i] = x[i];
     }
}

我知道它将为x抛出IndexOutOfBounds错误,但是我觉得必须有一个比这个更简单的方法,对吧?

I know it will throw an IndexOutOfBounds error for x, but I feel there must be a simpler method than this, right?

推荐答案

实际上,只有一个for循环可以实现您的功能.

Actually, only one for-loop can implement your function.

    int[] x = {7, 6, 6, 5, 3, 2, 1 };
    //Declare an int array with length = x.length+1;
    int[] bigger = new int[x.length+1];
    int add = 4;
    /** Define a variable to indicate that if a property location is found.*/
    boolean found = false;
    /** Define a variable to store an index for insert*/
    int indexToInsert = 0;
    for (int i = 0; i < x.length; i++){
         if ( !found && add >= x[i]){
             found = true;
             indexToInsert = i;
             bigger[indexToInsert] = add;
             i--;
         }
         else{
             if(found)
             {
                 bigger[i+1] = x[i]; 
             }else
             {
                 bigger[i] = x[i];
             }

         }
    }

    /*
     * If a property index is not found. Then put the value at last. 
     */
    if(!found)
    {
        indexToInsert = x.length;//
        bigger[indexToInsert] = add;
    }

一些示例如下运行:

初始数组为 [7、6、6、5、3、2、1]

添加= 4

 [7, 6, 6, 5, 4, 3, 2, 1]

添加= -1

 [7, 6, 6, 5, 3, 2, 1, -1]

添加= 100

 [100, 7, 6, 6, 5, 3, 2, 1]

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

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