2016-06-07 162 views
-2
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; 
} 

我理解選擇排序的概念,但代碼讓我感到困惑。特別是,有人可以解釋從「int temp = array [i];」開始的外部for循環的最後三條語句中發生了什麼。需要幫助瞭解代碼段

+1

http://stackoverflow.com/questions/13766209/effective-swapping-of-elements-of-an-array-in-java –

+0

您可以切換「數組[array] [數組] [數組[最高索引] '。要做到這一點,你需要複製'array [i]',這樣你可以在被array [i] = array [highestIndex];'覆蓋之後訪問該值。 – Gendarme

回答

2

這是着名的交換程序。像Java,當你想換一個名爲兩個變量的值語言說ab,你不得不求助於在您使用第三個變量在運輸過程中保存的值這樣一個例行:

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. 

在一些其他語言,如a, b = b, a構造可用於此目的,這在我看來更直觀。

在選擇排序,內環已經找到指數保持最高值的元素後,你需要交換它與該外環指數持有的元素,那就是,這達到在上下文。

+0

謝謝,這就是我一直在尋找的東西。我知道兩個值正在交換,但我不明白它是如何影響其餘代碼的。 –