【问题标题】:How to put greater words at the end when using insertion sort?使用插入排序时如何将更大的单词放在末尾?
【发布时间】:2021-03-19 12:22:05
【问题描述】:

我正在编写一些将我的字符串按字母顺序组织的代码,但我意识到当一个单词大于其他所有单词时,它会将它放在前面。我如何让它被放在单词列表的后面?


public class SortingText {
    public static void main(String[] args) {
          int i,j;
          String key;
          String[] inputArray = {"Fourscore","and","seven","years","ago","our"};
          System.out.println(Arrays.toString(inputArray));
          for (j = 1; j < inputArray.length; j++) { //the condition has changed
            key = inputArray[j];
            i = j - 1;
            while (i >= 0) {
              if (key.compareTo(inputArray[i]) > 0) {//here too
                break;
              }
              inputArray[i + 1] = inputArray[i];
              i--;
            }
            inputArray[i + 1] = key;
            System.out.println(Arrays.toString(inputArray));
          }
          System.out.println(Arrays.toString(inputArray));
        }
}

【问题讨论】:

  • 您的问题不在于字长,而在于您不区分大小写并且区分大写和非大写字母。大写字母在您的逻辑中首先排序。尝试将第一个单词更改为“fourscore”,您会发现尽管它很长,但它不会在开头排序

标签: java arrays insertion-sort compareto


【解决方案1】:

目前,您使用 compareTo 比较这 2 个项目。让我们更新它以使用比较器:

// Sort by the natural order
Comparator<string> cmp = Comparator.naturalOrder();
...
if (cmp.compare(key, inputArray[i]) > 0) {//here too

由于您希望在排序过程中忽略大小写,因此需要使用不区分大小写的比较器:

Comparator cmp =  String.CASE_INSENSITIVE_ORDER;
// Result = [ago, and, Fourscore, our, seven, years]

【讨论】:

    【解决方案2】:

    String.compareTo() 区分大小写,这意味着Aa“小”。这就是为什么"Fourscore" 位于排序数组的开头。

    比较元素时可以使用compareToIgnoreCase() 代替compareTo() 忽略大小写:

    if (key.compareToIgnoreCase(inputArray[i]) > 0) {
    

    Demo

    【讨论】:

      猜你喜欢
      • 2014-08-09
      • 2020-04-17
      • 1970-01-01
      • 2016-10-08
      • 1970-01-01
      • 2011-08-15
      • 2016-09-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多