【问题标题】:Selection sort: storing value instead of index选择排序:存储值而不是索引
【发布时间】:2019-12-21 00:23:31
【问题描述】:

我正在研究排序算法,包括选择排序,所以我决定写一个方法,它工作正常,但是当我检查这本书时,它有 2 个变量,所以我检查了它,发现它使用一个变量来存储当前索引和另一个作为临时交换

而我的只有临时变量,它也将索引中的初始 存储为最低值,然后将其与数组中的其他值进行比较,如果找到更大的值则交换。

这是我的代码:

public static void selectionSort(int[] arr){
int lowest;
for(int i = 0; i < arr.length - 1; i++){
  lowest = arr[i];
  for(int j = i+1; j<arr.length; j++){
    if(arr[j]<lowest){
      lowest = arr[j];
      arr[j] = arr[i];
      arr[i] = lowest;
    }
   } 
  }
 }

这是这本书的

public static void selectionSort(int[] list){   
    int min; 
    int temp;
    for(int i = 0; i < list.length - 1; i++) { 
        min = i;
        for(int j = i + 1; j < list.length; j++)
            if( list[j] < list[min] )
                min = j;
        temp = list[i];
        list[i] = list[min];
        list[min] = temp;
    }
}

所以我在网上看了看,所有的都和书上的一样,所以我的代码是坏的还是慢的,或者它不被认为是选择排序?

抱歉有任何英文错误:P

【问题讨论】:

  • 请记住,当人们编写排序时,他们通常不知道被排序的事物的类型,只是知道它顺序并且可以进行比较。
  • 对于此类问题,请前往software engineering

标签: java selection-sort


【解决方案1】:

所以,原来的代码是这样工作的:

Start with the first element of the array
Find the smallest number in the array
Swap the two numbers
Repeat the process Until You reach the end of the list

当你这样做时:

Start with the first element of the array
For each element smaller than the current Swap the two numbers
Replace the lowest number with the swapped
Repeat the process

结果应该是一样的,但可能你交换的数字比第一个多。这可能会使它比原来的慢一点。

实际上它现在看起来有点像插入排序,所以基本上你正在用所有比你拥有的更大的元素交换元素。

【讨论】:

  • 是的,我让它在每次交换后打印数组,发现它是一个插入。这很尴尬:P
【解决方案2】:

看起来你在嵌套的 for 循环中进行了更多的交换。

如果你做一个 [4,3,2,1] 会发生什么?我认为您将进行比实际 selectionSort 更多的交换操作。

我不确定您的代码是坏还是慢。 众所周知,SelectionSort 是正确的,但速度也不快。

【讨论】:

  • 你可能无意中改进了它:-)
  • 是的,原来我做了很多交换,6 次交换 [4,3,2,1]。用 break 语句修复它。但事实证明,我做的更多的是插入排序而不是选择:P 谢谢。
猜你喜欢
  • 1970-01-01
  • 2017-06-25
  • 2018-05-10
  • 2014-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-29
相关资源
最近更新 更多