将元素插入数组并返回索引,以便在完整数组的情况下重新分配数组

时间:2014-04-13 15:15:28

标签: java arrays insert indexing

我需要实现一个方法 public int insert(int x),它在"元素中插入x"数组保持有序,并返回输入的索引; 如果元素已经存在,则不要插入x并返回-1;如果数组已满,则重新分配"元素"数组中的数组为double size,然后插入项x。 我知道API中可能已有类似的方法,而是实现它。

我写了这个,但我不知道如何完成它......

public int insert(int x)  {
    if(numElements == elements.length) {
                //code
            }   
    int pos = binarySearch(x);
    if(pos != -1) 
        return -1;
    if(elements[-(pos + 1)] != null) {
        for(int i = numElements; i >= -(pos + 1); i--)
            elements[i + 1] = elements[i];
    }
    elements[-(pos + 1)] = x;
    numElements++;
    return -(pos + 1);
}

然而,我不知道我所写的内容是否正确,我想念一个完整数组的情况。谁能帮我? 感谢


private int binarySearch(int x) {
    int inf = 0;
    int sup = numElements - 1;
    if(sup == -1 || elements[0] > x)
        return -1;
    if(elements[sup] < x)
        return -(numElements + 1);
    //Invariante di ciclo: se x in a, allora x in a[inf...sup]
    while(inf <= sup) {
        int i = (inf  + sup) >>> 1; //divide per due
        if(elements[i] > x)
            sup = i - 1;
        else if(elements[i] < x)
            inf = i + 1;
        else
            return i;
    }
    return -(inf + 1);
}

1 个答案:

答案 0 :(得分:0)

你走了。

我所做的是创建一个大小为两倍的新数组,然后使用System.arraycopy移动现有元素。最后,我将放大的数组的引用分配给elements变量。

我使用System.arraycopy因为它比手动制作的循环复制更快。它使用JVM的本机实现。

我还用System.arraycopy替换了数组位移检查和for循环。 此外, - (pos + 1)给你一个负数。

public int insert(int x)  {
    if(numElements == elements.length) {
         int[] enlargedElements = new int[elements.length * 2];
         System.arraycopy(elements, 0, enlargedElements, 0, elements.length);
         elements = enlargedElements;
    }   
    int pos = binarySearch(x);
    if(pos == -1) 
        return -1;
    if(pos < numElements) {
        System.arraycopy(elements, pos, elements, pos + 1, numElements - pos);
    }
    elements[pos] = x;
    numElements++;
    return pos;
}

private int binarySearch(int x) {
    int inf = 0;
    int sup = numElements - 1;
    if(sup == -1 || elements[0] > x)
        return 0;
    if(elements[sup] < x)
        return numElements;
    //Invariante di ciclo: se x in a, allora x in a[inf...sup]
    while(inf <= sup) {
        int i = (inf  + sup) >>> 1; //divide per due
        if(elements[i] > x)
            sup = i - 1;
        else if(elements[i] < x)
            inf = i + 1;
        else
            return -1;
    }
    return inf;
}