2014-06-21 58 views
0

我想運行選擇排序,看看它是如何工作的,顯然,我沒有按預期工作的代碼,有人可以幫我指出我做錯了什麼? 我知道交換部分時出錯,但我不知道爲什麼。爲什麼我的選擇排序根本不排序?

public class SortingAlgorithm 
{ 
private long timeRun; 

public SortingAlgorithm() 
{ 
    timeRun = 0; 
} 

public long getTimeRun() 
{ 
    return timeRun; 
} 

public void setTimeRun(long timeRun) 
{ 
    this.timeRun = timeRun; 
} 

private void swap(int a, int b, int[] arrB) 
{ 
    int temp = arrB[a]; 
    arrB[a] = arrB[b]; 
    arrB[b] = temp; 
} 
public int[] selection(int[] arr, int length) 
{ 
    long startTime = System.nanoTime(); 
    for(int i= 0; i<length-1; i++) 
    { 
     for(int k = i+1; k<length; k++) 
     { 
      if(arr[i] > arr[k]) 
      { 
       swap(arr[i], arr[k], arr); 
      } 
     } 
    } 
    timeRun = System.nanoTime() - startTime; 
    return arr; 

} 

}

這裏是驅動程序:

import java.util.*; 
public class Driver 
{ 
     private static int length = 10; 
     private static int[] arr = new int [length]; 
     public static void main(String [] args) 
{ 
    Random rand = new Random(); 
    //seed the array 
    for(int counter = 0; counter < length ;counter++) 
    { 
     arr[counter] = rand.nextInt(10); 
    } 

    SortingAlgorithm tool = new SortingAlgorithm(); 
    arr = tool.selection(arr, length); 

    for(int i = 0; i < length ;i++) 
    { 
     System.out.println(arr[i]); 
    } 

    System.out.println(tool.getTimeRun()); 
} 

}

回答

2

當你打電話的交換,你在數組元素傳遞:

swap(arr[i], arr[k], arr); 

但你的函數預計這些指數將上漲e數組。你應該這樣調用它:

swap(i, k, arr); 
+0

我想我剛達到一個新的水平愚蠢......謝謝你CDAHN – Rozen