首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >选择排序方法

选择排序方法
EN

Stack Overflow用户
提问于 2015-09-08 09:21:02
回答 2查看 115关注 0票数 1

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

代码语言:javascript
复制
// 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;
}
EN

回答 2

Stack Overflow用户

发布于 2016-04-15 15:00:46

类排序{

代码语言:javascript
复制
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);
}

}

票数 0
EN

Stack Overflow用户

发布于 2015-09-08 09:36:30

您可以使用Collections.sort()

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32447916

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档