【问题标题】:Method to introduce a new String object into an array of Strings while maintaining the Lexicographical order在保持字典顺序的同时将新的字符串对象引入字符串数组的方法
【发布时间】:2013-04-29 02:43:57
【问题描述】:

旁注:

我想通过 Array 类而不是 ArrayList 来做到这一点。

您可以假设字符串数组中的字符串已经按正确的字典顺序(按字母顺序列出)进行组织。

例如:

如果数组是 -> String[] list = {"Bacon","Cheese","Milk","Pancake","Yogurt"};

我想将字符串“OJ”添加到组合中,它应该如下所示:

{"培根","奶酪","牛奶","OJ","煎饼","酸奶"}

提前致谢!

【问题讨论】:

  • 您反对转换为arraylist 来完成排序吗?
  • 即使是 ArrayList 类也不值得这个功能。您正在寻找TreeSet<String>。由于您想使用普通数组来保留它(可能是因为是作业),您应该寻找Insertion Sort,特别是在桶中插入元素并将所有元素移动到右侧的算法。
  • @tieTYT,是的,我想只通过数组来做。
  • @LuiggiMendoza 我会调查的,谢谢。您介意输入一些示例代码来帮助我更好地理解吗?
  • 因为这是作业,我可以为你写一个算法,但根本没有代码。

标签: java arrays string methods


【解决方案1】:

使用 java.util.Arrays.binarySearch(...)。

您将不得不增加数组的大小。这听起来像家庭作业。 TreeSet 是一个更易于使用的类。

【讨论】:

  • Arrays#binarySearch 用于不在数组中的元素时将返回 -1,因此 OP 应手动查找该元素。
  • 不,它不会(除非字符串应该在开头插入
【解决方案2】:

您可以将新条目附加到数组的末尾,然后对其进行排序。

【讨论】:

  • 这是一个 O(N^2) 的解决方案,因为数组已经排序,所以不值得。
【解决方案3】:

插入排序的简单方法:

public class InsertionSort {

    public static void main(String[] args) {
        String[] list = {"Bacon", "Cheese", "Milk", "Pancake", "Yogurt", "OJ"};

        InsertionSort in = new InsertionSort();
        list = in.insertSort(list);

        for (String str : list) {
            System.out.println(str);
        }
    }

    public String[] insertSort(String[] list) {
        for (int i = 1; i < list.length; i++) {
            String val = list[i];
            int value = list[i].toLowerCase().charAt(0);
            int j = i - 1;
            while (j >= 0 && list[j].toLowerCase().charAt(0) > value) {
                list[j + 1] = list[j];
                j = j - 1;
            }
            list[j + 1] = val;
        }

        return list;
    }
}

算法取自here:

public static void insertSort(int[] A){
  for(int i = 1; i < A.length; i++){
    int value = A[i];
    int j = i - 1;
    while(j >= 0 && A[j] > value){
      A[j + 1] = A[j];
      j = j - 1;
    }
    A[j + 1] = value;
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2021-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多