按顺序将String插入数组中

时间:2016-04-16 19:03:07

标签: java

我有一个已按字母顺序排列的字符串列表。这里我们假设用户按字母顺序输入项目。

我有一个类中的字符串项列表和一个方法,其中有人可以传入另一个字符串对象以插入到数组中。

String[] strings = new Strings[0];

public void add(String a){
//here the current list is resized and we need to add the new item
Strings[] newSizedList = new String[strings.length+1];
//for loop here to copy items over into the new resized array.
}

问题是,该列表已被假定为按字母顺序排列。我需要做的是将传入的字符串插入到数组中的正确位置,同时仍然按字母顺序保留其他项。

限制是我不想使用任何类型的"排序算法"。换句话说,我不想立刻对整个列表进行排序并按顺序排列。

我想保持项目的顺序,因为它已经按顺序排列,但是将当前项目插入列表中的相应位置。

我不能使用任何Collection静态方法或Java集合类静态方法

有谁知道如何做到这一点?

3 个答案:

答案 0 :(得分:1)

因为你要使用for循环克隆数组,所以不需要在这里做任何类型的排序(这应该是好消息,因为你说这不是一个选项)。只需将新物品插入正确的位置即可。

//for loop here to copy items over into the new resized array.
//We use two counters here, ii for the old list and i for the new
int ii = 0, nn = strings.length;
for(int i = 0, n = newSizedList.length; i < n; i++) {

    if(ii != nn && (ii != i || strings[ii].compareTo(a) < 0)){
        //The item in newSizedList[i] will be taken from the original list if
        //we have not already taken all the items from there (ii != nn) and
        //a) we have already inserted the new item (ii != i)
        //or b) a is alphabetically "greater" than the corresponding item in original array
        newSizedList[i] = strings[ii];
        ii++;//Keep the other counter in sync
    } else  {
        //Otherwise, this is the place for the new item
        newSizedList[i] = a;
    }

}

答案 1 :(得分:0)

Arrays.binarySearch可用于有效地找到正确的插入点。

答案 2 :(得分:0)

只需在Arrays类中调用正确的方法。

Arrays.sort(newSizedList);
相关问题