【问题标题】:Modified selection sort that selects the biggest number选择最大数的修改选择排序
【发布时间】:2016-04-03 02:35:24
【问题描述】:

我正在尝试编写一个修改后的选择排序,它选择最大的数字并将其放在列表的末尾。我遇到了一个问题。代码有点排序列表,但并不完美。这是我运行代码后的结果: 选择排序前:[2, 8, 7, 1, 3, 5, 9, 4, 6] 选择排序后:[1, 2, 8, 7, 3, 4, 5, 9, 6]

这是我的代码:

public static int[] sort(int[] list) {
int i, j, maxNum, maxInde, temp = 0;
    for (i = list.length-1; i >= 0; i--) {
        maxNum = list[i];
        maxInde = i;
        for (j = i; j < list.length; j++) {
            if (list[j] < maxNum) {
                maxNum = list[j];
                maxInde = j;
            }
        }
        if (maxNum < list[i]) {
            temp = list[i];
            list[i] = list[maxInde];
            list[maxInde] = temp;
        }
    }
    return list;
}  

我不知道问题出在哪里。

【问题讨论】:

  • 如果我记得选择排序正确,是不是需要一个额外的数组来存储排序后的数组?
  • 我正在交换下面的索引,所以它不需要另一个数组

标签: java arrays sorting selection sorted


【解决方案1】:

该算法在概念上存在缺陷,因为您将数组从n-1 向下扫描到0,并在每次迭代时从子数组a[n-1,...,i] 中选择最大元素。这个子数组应该总是被排序的(并且应该由数组的n-i 最大元素组成)---这类似于经典选择排序的循环不变量---以及要插入当前位置的最大元素应该来自另一个子数组,即a[i,...,0]

另外,正如 cmets 中提到的,不需要返回数组,因为算法可以修改它。

【讨论】:

    【解决方案2】:

    这里是固定版本:

    int i, j, maxNum, maxInde, temp = 0;
    for (i = list.length-1; i >= 0; i--) {
    // you start iterating from the end of the list 
    // which means that the elements between i and the end of the list are sorted
        maxNum = list[i];
        maxInde = i;
        for (j = 0; j < i; j++) { 
        // you have to iterate through the nonsorted elements
            if (list[j] > maxNum) {
                maxNum = list[j];
                maxInde = j;
            }
        }
        if (maxNum > list[i]) {
        // if you found an element that is bigger then the current element
        // then it should be set as the current element
            temp = list[i];
            list[i] = list[maxInde];
            list[maxInde] = temp;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-12-16
      • 2020-12-07
      • 2021-06-13
      • 2013-04-25
      • 1970-01-01
      • 2019-01-13
      • 1970-01-01
      相关资源
      最近更新 更多