Java 选择排序:存储值而不是索引

Java 选择排序:存储值而不是索引,java,selection-sort,Java,Selection Sort,我正在研究排序算法,包括选择排序,所以我决定写一个方法,它工作得很好,但当我检查这本书时,它有两个变量,所以我检查了它,发现它使用一个变量存储当前索引,另一个作为临时交换 而mine只有一个临时变量,该变量也将索引中的初始值存储为最低值,然后将其与数组中的其他值进行比较,如果发现较大的值,则进行交换 这是我的密码: public static void selectionSort(int[] arr){ int lowest; for(int i = 0; i < arr.length -

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

而mine只有一个临时变量,该变量也将索引中的初始值存储为最低值,然后将其与数组中的其他值进行比较,如果发现较大的值,则进行交换

这是我的密码:

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;
    }
   } 
  }
 }
publicstaticvoidselectionsort(int[]arr){
int最低;
对于(int i=0;ifor(int j=i+1;j看起来您在嵌套for循环中进行了更多的交换

如果你做一种[4,3,2,1],会发生什么?我想你会有比实际选择排序更多的交换操作

我不确定你的代码是坏还是慢。
SelectionSort已知是正确的,但它也不快。

因此,原始代码的工作原理如下:

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
结果应该是一样的,但可能你交换的数字比第一个多。这可能会使交换比原来的慢一点


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

请记住,当人们编写排序时,他们通常不知道要排序的东西的类型,只是它有一个顺序并且可以比较。对于像这样的问题,你可以y无意中改进了它:-)是的,我做了很多交换,6次交换[4,3,2,1]。用break语句修复了它。但事实证明我做的更多的是插入排序而不是选择:P谢谢。是的,我让它在每次交换后打印数组,发现它是一个插入。这很尴尬:P
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