【问题标题】:Doing a Selection sort on an ArrayList对 ArrayList 进行选择排序
【发布时间】:2013-11-06 04:58:43
【问题描述】:

我需要根据“值”从最高到最低对数组列表进行排序,我真的卡住了:(基本上在这个项目中,他们将运行一个项目列表,这个方法应该把一个与首先是最高值,所以我尝试使用选择排序。提前感谢您的帮助:) 这是我目前所拥有的

public void pickMostExpensiveFirst(ArrayList<Item> totalListOfItems)
{
    int max, i ,j;
    Item temp;

    for (i = 0; i < totalListOfItems.size() - 1; i++)
    {
        max = i;

        for (j = i + 1; j < totalListOfItems.size(); j++)
        {
            if (totalListOfItems.get(max).getValue()
                    .compareTo(totalListOfItems.get(j).getValue()) > 0)
                max = j;
        }

        temp = totalListOfItems.get(i);
        totalListOfItems.set(i, totalListOfItems.get(max));
        totalListOfItems.set(max, temp);
    }
}

【问题讨论】:

    标签: java sorting arraylist selection-sort


    【解决方案1】:

    你的问题在这里:

    if (totalListOfItems.get(max).getValue().compareTo(totalListOfItems.get(j).getValue()) > 0)
      max = j;
    

    在这里你比较位置 max 和 j 的 item,如果 item(max) > item(j),你用 j 替换 max。这基本上是在搜索 LOWEST 值,而不是 HIGHEST。切换一下,你的问题就解决了。

    【讨论】:

      【解决方案2】:

      Java 帮助面向对象编程,当 Java 集合框架(以及支持类)提供现成的经过验证的解决方案时,为什么要从头开始实现。

      如果您的方法的目标只是识别最大值/最小值或排序列表,那么 java.util.Collections 类提供了 util 方法。唯一的要求是您的 Item 类应该是(IsA 关系)Comparable,这意味着 Item 应该实现 Comparable 接口。如果您无法控制 Item 类代码,那么我们可以使用 Interface Comparator 提供比较规则。示例代码如下所示。

      public static void pickMostExpensiveFirst(ArrayList<Item> totalListOfItems) {
          System.out.println(Collections.max(totalListOfItems));
          // Collections.sort(totalListOfItems); // to sort with Comparable
          // Collections.sort(totalListOfItems, ValueComparator); // to sort with
          //                                                         Comparator
      }
      
      class Item implements Comparable<Item> {
          String name;
          int value;
      
          public Item(String name, int value) {
              this.name = name;
              this.value = value;
          }
      
          @Override
          public int compareTo(Item other) {
              return Integer.compare(this.value, other.value);
              // return -1 * Integer.compare(this.value, other.value); in case you 
                                                           //need descending order
      
          }
      
          @Override
          public String toString() {
              return name + " " + value;
          }
      
      }
      

      【讨论】:

      • 请注意,由于 Java 8 Comparator.comparing(Item::getValue) 快速而紧凑地生成所需的 Comparator 对象。如果需要反向逻辑,请附加 reversed() 调用。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-24
      • 1970-01-01
      • 1970-01-01
      • 2016-08-28
      • 1970-01-01
      相关资源
      最近更新 更多