2016-12-15 51 views
0

我試圖通過'簡單'的練習來學習代碼。我正在嘗試使用選擇排序來進行搜索算法。當我遵循頭腦中的代碼時,它非常有意義,但是當我運行它時,它不會排序。對於數組,我使用的只是一個整數數組,它由隨機數組成,並且是隨機數。使用選擇排序在java中排序整數數組。找不到我的錯誤

int currentMin; 
    int currentMinIndex = 0; 
    int temp; 
    for(int i=0;i<array.length-1;i++){ 
     currentMin = array[i]; 
     for(int j=i+1;j<array.length-1;j++){ 
      if(array[j]<currentMin){ 
       currentMinIndex = j; 
       currentMin = array[j]; 
      } 
     } 
     temp = array[currentMinIndex]; //I am aware this could be currentMin 
     array[currentMinIndex] = array[i]; 
     array[i] = temp; 
    } 

我希望有人會發現我的錯誤,並告訴我。 (如果你有其他'簡單'的練習,我可以做,創造力是讚賞,但是這篇文章必須留在話題上)

編輯:我只是注意到,在一些奇怪的方式,當數組長度很長,但它排序最後一個。 (陣列長度因隨機而變化)

+0

我有事要告訴你呢! [你不必再跟着你的腦袋裏的代碼。](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – shmosel

+2

內循環需要去' array.length'(刪除'-1') – 4castle

+0

我已經寫下來了,然後寫下每個變量。所有警告都已打開。我想我已經破壞了代碼,idk如何進一步。我已經完成了測試部分。我很抱歉只是傻。 – Marekkk

回答

2

您需要更新currentMinIndexi當您設置currentMin,你的內循環應該是array.length

currentMin = array[i]; 
currentMinIndex = i; 
for(int j=i+1;j<array.length;j++){ 

你可以進一步通過移動聲明進入循環和消除temp(因爲你有currentMin)像

for (int i = 0; i < array.length - 1; i++) { 
    int currentMin = array[i]; 
    int currentMinIndex = i; 
    for (int j = i + 1; j < array.length; j++) { 
     if (array[j] < currentMin) { 
      currentMinIndex = j; 
      currentMin = array[j]; 
     } 
    } 
    array[currentMinIndex] = array[i]; 
    array[i] = currentMin; 
} 
0

你的兩個循環都跳過了最後一個元素。考慮在循環條件中使用<=而不是<來考慮最後一個元素。

1

有兩個問題

  1. 你忘了復位簡化該currentMinIndex
  2. 內部for循環的邊界條件不正確

這裏是你的代碼的修改版本:

public class SelectionSort { 

    public static void main(String[] args) { 
     int currentMin; 
     int currentMinIndex = 0; 
     int temp; 
     int[] array = {9, 1, 3, 2, 4, 7}; 
     for(int i=0;i<array.length-1;i++){ 
      currentMin = array[i]; 
      currentMinIndex = i;     // Problem #1 
      for(int j=i+1;j<=array.length-1;j++){ // Problem #2 
       if(array[j]<currentMin){ 
        currentMinIndex = j; 
        currentMin = array[j]; 
       } 
      } 
      temp = array[currentMinIndex]; //I am aware this could be currentMin 
      array[currentMinIndex] = array[i]; 
      array[i] = temp; 
     } 

     StringBuilder sb = new StringBuilder(); 
     sb.append("["); 
     String comma = "";  // first time special 
     for (int i=0; i<array.length; i++) { 
      sb.append(comma + array[i]); 
      comma = ", ";  // second time and onwards 
     } 
     sb.append("]"); 
     System.out.println(sb.toString()); 
    } 
} 

這個程序的輸出是

[1, 2, 3, 4, 7, 9]