选择排序方法

时间:2015-09-08 01:21:02

标签: java sorting arraylist selection-sort

所以这是一个有点愚蠢的问题,但是我的classSort方法存在问题。它每次都交换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;
}

2 个答案:

答案 0 :(得分:0)

class Sort {

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);
}

}

答案 1 :(得分:-1)

您可以使用Collections.sort()