Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/sorting/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 需要帮助理解代码段吗_Java_Sorting_For Loop_Selection_Selection Sort - Fatal编程技术网

Java 需要帮助理解代码段吗

Java 需要帮助理解代码段吗,java,sorting,for-loop,selection,selection-sort,Java,Sorting,For Loop,Selection,Selection Sort,我理解选择排序的概念,但代码让我感到困惑。具体来说,有人能解释一下以“int temp=array[i];”开头的外部for循环的最后三条语句中发生了什么吗?这是著名的交换例程。在Java等语言中,当您想交换两个变量(例如a和b)的值时,您必须求助于这样一个例程,即使用第三个变量来保存传输中的值: public int[] selectionSort(int array[]) { for(int i = array.length - 1; i >= 0; i--) {

我理解选择排序的概念,但代码让我感到困惑。具体来说,有人能解释一下以“int temp=array[i];”开头的外部for循环的最后三条语句中发生了什么吗?

这是著名的交换例程。在Java等语言中,当您想交换两个变量(例如
a
b
)的值时,您必须求助于这样一个例程,即使用第三个变量来保存传输中的值:

public int[] selectionSort(int array[]) {

    for(int i = array.length - 1; i >= 0; i--) { 
        int highestIndex = i;

        for(int j = i; j >= 0; j--) {
            if(array[j] > array[highestIndex])
                highestIndex = j;
        }
        int temp = array[i];
        array[i] = array[highestIndex];
        array[highestIndex] = temp;
    }
    return array;
}
在其他一些语言中,类似于
a,b=b,a
的构造可用于此目的,在我看来这更直观


在选择排序中,在内部循环找到包含最高值的元素的索引后,您需要将其与外部循环索引包含的元素交换,这就是在该上下文中实现的。

您可以切换
array[i]
array[highestIndex]
的位置。为此,您需要制作一份
array[i]
的副本,以便在该值被
array[i]=array[highestIndex]覆盖后可以访问该值。谢谢,这就是我要找的。我知道两个值正在交换,但我不明白它是如何影响代码的其余部分的。
int a = 2; 
int b = 6;
int tmp = a; // now tmp has a value that is _copy_ of a i.e. 2
a = b;  // since we saved a in tmp, we can _mutate_ it, now a has b's value
b = tmp; // swap! here, b = a won't work because a contains b's current value.
// now a has value 6 and b has value 2, exactly what we wanted.