将两个字符串数组合成字母顺序

时间:2017-11-28 16:15:06

标签: java arrays sorting compareto array-merge

我有两个字符串数组,我试图将它们组合成一个数组。这两个数组按字母顺序排列。我必须将它们按字母顺序组合。我尝试这样做的方法是创建组合列表作为第一个列表,然后是第二个列表,然后对它们进行排序。不幸的是,我班级的讲师说他们希望我使用compareTo方法在一个步骤中对它们进行组合和排序。以下是我的代码,我将如何实现这一目标? 前两个数组是用户输入的值,按字母顺序最多10,000个单词,其余为null,例如:

  

list1 = {“Alfred”,“Bev”,“Carl”,“Dan”,null等。)

     

list2 = {“Bob”,“Craig”,“Dean”,“Fran”,null等。)

     

list3目标:{“Alfred”,“Bev”,“Bob”,“Carl”,Craig“,”Dan“,”Dean“,   “弗兰”}

    for (int b = 0; b < list3.length; b++)//adds list1 to merged array 
    {
        if (list1[b] != null) {
            list3[b] = list1[b];
            f++;
        }

    }
    int x = 0;
    for (int y = f; y < list3.length; y++)//adds list2 to merged array
    {
        if (list2[x] != null) {
            list3[y] = list2[x];
            x++;
        }
    }

    for (int q = 0; q < list3.length; q++)//Merged array in alphabetical order
    {
        if (list3[q] != null) {
            for (int b = q; b < list3.length; b++) {
                if (list3[b] != null) {
                    if (list3[q].compareTo(list3[b]) > 0) {
                        String s = list3[q];
                        list3[q] = list3[b];
                        list3[b] = s;

                    }

                }
            }
        }

    }

这是我第一次使用Stack Exchange,所以希望一切都格式正确!对不起任何错误。

2 个答案:

答案 0 :(得分:0)

如果你想同时合并和排序,你可以在一个包含String数组的类中实现InsertionSort(当你添加一个新数组或者用最终长度启动它时,你将增加它的大小)

您的步骤如下:

start with a array of lenght = list1.lenght + list2.lenght (called result here)
for each value on list1 and list2
compare if its lesser of the first element on the result array
if it is, add it before it and swap all list to the next position
if it is not, compare to the second and insert as its place if lesser and so on

对于合并然后排序:

Ssorting使用Arrays.sort(String [])

此外,您可以使用System.arraycopy方法复制数组的内容。

您的代码可以像以下一样简单:

String[] list3 = new String[list1.lenght + list2.lenght];
System.arraycopy(list1, 0, list3, 0, list1.lenght);
System.arraycopy(list2, 0, list3, list1.lenght, list2.lenght);
Arrays.sort(list3);

这里list3有你想要的结果。

答案 1 :(得分:0)

假设你可以使用集合,这样的东西可以解决问题。如果您不能使用收藏品,请告诉我,我将提供替代解决方案。

$td[0]->nodeValue

输出:

    String[] array1 = new String[] { "Alfred", "Bev", "Carl", "Dan" };
    String[] array2 = new String[] { "Bob", "Craig", "Dean", "Fran" };

    List<String> list1 = Arrays.asList(array1);
    List<String> list2 = Arrays.asList(array2);

    List<String> combined = new ArrayList<String>();
    combined.addAll(list1);
    combined.addAll(list2);

    System.out.println("Unsorted list: "+ combined.toString());

    Collections.sort(combined);

    System.out.println("Sorted list: "+ combined.toString());