2016-12-24 45 views
-1

所以我有這樣的代碼爲我的選擇排序:選擇排序的算法問題

public static void selectionSort(int[] arrayToSort){ 
    int smallest; 
    for(int i = 0; i < arrayToSort.length; i++){ 
     smallest = i; 
     for(int j = i+1; j < arrayToSort.length; j++){ 
      if(arrayToSort[j] < arrayToSort[smallest]){ 
       smallest = j; 
      } 
      if(smallest != i){ 
       int temp = arrayToSort[i]; 
       arrayToSort[i] = arrayToSort[smallest]; 
       arrayToSort[smallest] = temp; 
      } 
     } 
    } 
} 

我生成與隨機數的int數組。我的選擇排序有時會對數組進行排序,有時它會對數組進行「幾乎」排序。除了極少數在錯誤位置的數字之外,該數組大部分將被排序。我無法弄清楚這裏出了什麼問題,有什麼想法?

一些測試結果,其中陣列並沒有完全排序:

***NON SORTED*** 
77 
53 
27 
58 
83 
***SORTED*** 
27 
53 
77 
58 
83 

***NON SORTED*** 
40 
87 
27 
48 
82 
***SORTED*** 
27 
40 
82 
48 
87 

回答

3

你的內環內碼的一部分,把它的外循環;

public static void selectionSort(int[] arrayToSort){ 
    int smallest; 
    for(int i = 0; i < arrayToSort.length; i++){ 
     smallest = i; 
     for(int j = i+1; j < arrayToSort.length; j++){ 
      if(arrayToSort[j] < arrayToSort[smallest]){ 
       smallest = j; 
      } 
     } 
     if(smallest != i){ 
      int temp = arrayToSort[i]; 
      arrayToSort[i] = arrayToSort[smallest]; 
      arrayToSort[smallest] = temp; 
     } 
    } 
} 

參見例如algorithm in Wikipedia

+0

哦,我明白這是怎麼搞的。謝謝! – Carlton

2

我這樣做,當我需要它大學項目

引用:selection algoritm with figure

selection sort

public static void selectionSort(int[] arr){ 
     for (int i = 0; i < arr.length - 1; i++) 
     { 
      int index = i; 
      for (int j = i + 1; j < arr.length; j++){ 
       if (arr[j] < arr[index]){ 
        index = j;//searching for lowest index 
       } 
      } 
      int smallerNumber = arr[index]; 
      arr[index] = arr[i]; 
      arr[i] = smallerNumber; 
     } 
    } 
+0

感謝您的投票..對於初學者來說,它很難獲得聲望..我是新的堆棧溢出非常感謝你! –

0

這裏第二福爾內循環,如果你發現這是比我少(或最少)你正在做的這是這裏不需要交換操作的任何元素。在選擇排序中,您需要從未排序的數組中獲取最小元素並與最左側的元素交換,並且該元素成爲排序數組的一部分。 只需在第二個內部循環之外保持交換爲了使它只對最小的元素進行交換操作。

for(int i = 0; i < arrayToSort.length; i++){ 
    smallest = i; 
    for(int j = i+1; j < arrayToSort.length; j++){ 
     if(arrayToSort[j] < arrayToSort[smallest]){ 
      smallest = j; 
     } 
    } 
    if(smallest != i){ 
     int temp = arrayToSort[i]; 
     arrayToSort[i] = arrayToSort[smallest]; 
     arrayToSort[smallest] = temp; 
    } 
}