Java 交换如何在选择排序中工作?
有人能解释一下为什么这个方法的交换部分是有效的吗?我已经使用这个方法有一段时间了,但是我不知道交换部分是如何工作的。如果有人能解释一下,我将不胜感激。多谢各位Java 交换如何在选择排序中工作?,java,Java,有人能解释一下为什么这个方法的交换部分是有效的吗?我已经使用这个方法有一段时间了,但是我不知道交换部分是如何工作的。如果有人能解释一下,我将不胜感激。多谢各位 public static int [] selectionSort(int [] num){ int min=0,minIndex=0; for(int i=0; i< num.length-1;i++){ min=num[i]; for(int x=i+
public static int [] selectionSort(int [] num){
int min=0,minIndex=0;
for(int i=0; i< num.length-1;i++){
min=num[i];
for(int x=i+1;x<num.length;x++){
if(min > num[x]){
min=num[x];
minIndex=x;
}
}
//this is the part Im so confused about
if(num[i]> min){
int temp=num[i];
num[i]=num[minIndex];
num[minIndex]=temp;
}
}
return num;
}
公共静态int[]selectionSort(int[]num){
int min=0,minIndex=0;
for(int i=0;imin){
int temp=num[i];
num[i]=num[minIndex];
num[minIndex]=温度;
}
}
返回num;
}
选择排序的整个概念是选择下一个最小元素的索引,并将其移动到正确的位置
在选择排序的每次迭代中,从未排序的子数组中选取最小元素(考虑升序),并将其移动到已排序的子数组中
以下示例说明了上述步骤:
int arr[] = {64, 25, 12, 22, 11}
Find the minimum element in arr[0...4]
and place it at beginning
*11* 25 12 22 64
Find the minimum element in arr[1...4]
and place it at beginning of arr[1...4]
11 *12* 25 22 64
Find the minimum element in arr[2...4]
and place it at beginning of arr[2...4]
11 12 *22* 25 64
Find the minimum element in arr[3...4]
and place it at beginning of arr[3...4]
11 12 22 *25* 64 (64 is automatically sorted)
在每个步骤中,您都可以找到minIndex
。然后将arr[minIndex]
中的值与arr[i]
中的值交换
因此,在迭代0
,minIndex
将是4
,因为11
位于索引4
,而i
当然是0
,因为它是第一次迭代。。。。等等
在迭代0中,
num[i]=>64
,以及num[maxIndex]=>11
int temp = num[i]; // temp => 64
num[i] = num[minIndex]; // num[i] = num[minIndex] => 11
num[minIndex] = temp; // num[minIndex] => 64
迭代0之后,
num[i]=>11
和num[maxIndex]=>64
由于Java中的变量不是用指针而是用它们的值来处理的(调用值而不是调用引用),因此需要分配一个临时变量来存储最小的值。因为您正在将num[i]设置为另一个数字,所以您需要能够稍后访问该数字
int temp=num[i]; //create temp variable to store the number in array num on index i
num[i]=num[minIndex]; // assign a new number to num on index i
num[minIndex]=temp; // now assign the temp number to num on index minIndex
什么让人困惑?它正在将索引
i
处的元素与索引minIndex
处的元素交换。尝试编写代码来交换两个变量的值,您就会明白。您的逐步解释是我缺少的链接,谢谢您的帮助help@Msinger很高兴我能帮忙。干杯