gpt4 book ai didi

java - 选择排序 : storing value instead of index

转载 作者:行者123 更新时间:2023-12-01 19:15:07 24 4
gpt4 key购买 nike

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

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

这是我的代码:

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

最佳答案

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

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

结果应该是相同的,但可能您交换的数字比第一个数字更多。这可能会比原来的速度慢一点。

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

关于java - 选择排序 : storing value instead of index,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59428286/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com