【问题标题】:Insertion Sort using compareto() in a arraylist of strings在字符串数组列表中使用 compareto() 进行插入排序
【发布时间】:2021-07-12 21:07:33
【问题描述】:
for(int i = 1; i < list.size(); i++)
{
  int j = i;    
  int orderNum = list.get(j).toLowerCase().compareTo(list.get(j - 1).toLowerCase());
  while(j > 0 && orderNum < 0)
  {
    String temp = list.get(j);
    list.set(j, list.get(j - 1));
    list.set(j - 1, temp);
    j--;
  }
}

所以我想按字母顺序使用插入排序对字符串的 ArrayList 进行排序,并且 ArrayList 是例如 ["boy", "Eat", "apple", "code", "Tea"] 但事实证明成为 ["code", "apple", "boy", "Eat", "Tea"] 所以即使我一直在查看我的代码,我也不知道发生了什么。

谢谢

【问题讨论】:

  • 排序工作正常。你能添加填充和排序调用部分吗?如果可能的话,连同执行输出一起。

标签: java sorting arraylist


【解决方案1】:

您的排序问题是 orderNum 必须在内部 while 循环中不断评估。但是您只在每个外部循环周期对其进行一次评估。因此最好删除该分配并将compareTo 放在while 循环条件中。您可以在algorithm 中看到这一点。

List<String> list = new ArrayList<>(List.of("boy", "Eat", "apple", "code", "Tea"));
for (int i = 1; i < list.size(); i++) {
    int j = i;
    while (j > 0 && list.get(j).toLowerCase()
            .compareTo(list.get(j - 1).toLowerCase()) < 0) {
        String temp = list.get(j);
        list.set(j, list.get(j - 1));
        list.set(j - 1, temp);
        j--;
    }
}
System.out.println(list);

打印

[apple, boy, code, Eat, Tea]

要使while statement 不那么混乱,您可以使用预定义的不区分大小写的比较器并将listindex 传递给lambda。它返回一个boolean 作为比较的结果。

BiFunction<List<String>, Integer, Boolean> comp = (lst, idx)->
       String.CASE_INSENSITIVE_ORDER.compare(list.get(idx), 
                                 list.get(idx-1))<0;
        

然后像这样使用它。

while (j > 0 && comp.apply(list,j)) {

【讨论】:

    猜你喜欢
    • 2012-08-20
    • 2020-11-12
    • 1970-01-01
    • 2018-02-15
    • 2011-04-24
    • 2014-05-11
    • 2017-09-26
    • 1970-01-01
    • 2017-10-28
    相关资源
    最近更新 更多