【问题标题】:Selection Sort Method选择排序方法
【发布时间】:2015-12-03 13:19:39
【问题描述】:

所以这是一个有点愚蠢的问题,但我在类上的 selectionSort 方法有问题。它每次都交换 ArrayList 数据,而不是仅在一项较小时交换。我知道这是一个括号问题,但我不知道在哪里删除/添加括号。

// Sort using selectionSort and call compareTo methods to evaluate
public static ArrayList selectionSort(ArrayList<Person> array) {
    int smallestIndex;
    Person smallestValue;

    for (int index = 1; index < array.size(); index++) {
        smallestValue = array.get(index);
        smallestIndex = index;

        for (int i = index + 1; i < array.size(); i++) {
            if (smallestValue.compareTo(array.get(i)) == 1) 
            {
                // update smallest
                smallestValue = array.get(i);
                smallestIndex = i;
            }
            // do nothing if the curIndex has the smallest value
            else if (smallestIndex == index)
                ;
            // swap values otherwise else
            else {
                Person temp = array.get(index);
                array.set(index, array.get(smallestIndex));
                array.set(smallestIndex, temp);

            }
        }
    }
    return array;
}

【问题讨论】:

  • index 不应该从 0 开始?请发布Person对象
  • 嗨实际上compareTo()String 工作但我可以在这里看到你实际上正在使用一个对象Person 该类是否覆盖compareTo 方法?然后请发布Person Class 你是如何覆盖的,因为你说每次迭代它的交换元素你的覆盖逻辑可能是错误的,
  • 您应该了解compareTo() 的工作原理:docs.oracle.com/javase/7/docs/api/java/lang/Comparable.html

标签: java sorting arraylist selection-sort


【解决方案1】:

类排序{

private List<Integer> list;

public Sort(List<Integer> list){
    this.list = list;       
}

public void selectionSort() {
    int idx = 0;
    int temp = 0;
    for(int i=0; i<list.size(); i++) {
        temp = list.get(i);
        for(int j=i; j<list.size(); j++){
            if(list.get(j) <= temp){
                temp = list.get(j);
                idx = j;                    
            }
        }
        swap(i,idx);
    }

}

private void swap(int x, int y) {
    int tmp = list.get(x);
    list.set(x, list.get(y));
    list.set(y, tmp);
}

}

【讨论】:

    【解决方案2】:

    您可以使用Collections.sort()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-05-20
      • 1970-01-01
      • 2021-02-06
      • 2016-11-01
      • 2019-04-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多