【问题标题】:Sorting elements using insertion sort使用插入排序对元素进行排序
【发布时间】:2021-12-30 18:16:36
【问题描述】:

如果我使用如下所示的插入排序,并且有一个数组,其中一些元素是整数,然后是一些为空的元素 - 我将如何使用插入排序对该数组进行排序,最后使用空元素?

例如:[1, 2, 6, null, 9, 5, 4, null, 2, 3] 收件人:[1, 2, 2, 3, 4, 5, 6, 9, null, null]

【问题讨论】:

    标签: java arrays sorting insertion


    【解决方案1】:

    可以用Comparator.nullsLast:

    public static <T extends Comparable<? super T>> void insertionSort(T[] array) {
        Comparator<T> comparator = Comparator.nullsLast(Comparator.naturalOrder());
        // ...
        int compareTo = sorted;
        while (compareTo >= 0 && comparator.compare(newElement, array[compareTo]) < 0) {
        // ...
    }
    

    我使用Comparator.naturalOrderComparable 比较标准转换为Comparator

    【讨论】:

      【解决方案2】:

      一种选择是编写一个处理nullcompareTo 函数:

      public static <T extends Comparable<? super T>> int compareTo(T a, T b)
      {
          if (a == null && b == null) return 0;
          if (a == null) return 1;
          if (b == null) return -1;
          return a.compareTo(b);
      }
      

      然后让插入排序使用:

      while (compareTo >= 0 && compareTo(newElement, array[compareTo]) < 0) {
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-05
        • 2020-03-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多