2013-12-08 113 views
0

所以,我有我的代碼,但我的號碼沒有排序。有什麼我失蹤?代碼不正確排序

我排序的代碼,沒有其他的方法,如印刷和例如:

public static int[] swapElement (int [] x, int index1, int index2) { 
     int t = x[index1]; 
     x[index1] = x[index2]; 
     x[index2] = t; 
     return x; 
    } 
     public static int[] sortArray (int [] x) { 
     int index = 0; 
     int i=0; 

     int[] toSort= new int[x.length]; 
     for(int m=0;m<x.length;m++){ 
     index = indexOfMaxInRange(x); 
     toSort=swapElement(x,i,index); 
     i++; 
     } 

     return toSort; 
    } 
     public static int indexOfMaxInRange (int[] x) { 
     int max = 0; 
     int i=0; 
     int maxLocation = 0; 
     while(i < x.length) { 
      if (x[i] > max) { 
       max = x[i]; 
       maxLocation= i; 

      } 
      i++; 
     }  
+3

_and一切工作fine_顯然不是。使用調試器來找出代碼的行爲與您期望的不同。 –

+0

'swapElement'可以是無效的,因爲傳遞的'toSort'參數將被改變。 –

回答

1
for(int m=0;m<x.length;m++){ 
    index = indexOfMaxInRange(x); 
    toSort=swapElement(x,i,index); 
    i++; 
} 

在這裏,你第一個最大元素放置在第一個,然後第二個,第三個,然後等指標。問題在於,不是找到第二大指數的第二大元素,第三大元素等於第三大元素,您只需交換最大的元素。

爲了解決這個問題,我建議你讓你的方法indexOfMaxInRange實現它的名字,通過指定一個範圍來搜索,而不是讓它看起來整個數組。

編輯:每個請求,這裏是你如何添加一個下限,以你的方法:

public static int indexOfMaxInRange (int[] x, int firstIndex) { 
    int max = Integer.MIN_VALUE; 
    int i=firstIndex; //note! initialize to min instead of 0 
    int maxLocation = firstIndex; 
    while(i < x.length) { 
     if (x[i] > max) { 
      max = x[i]; 
      maxLocation= i; 

     } 
     i++; 
    } 
    return maxLocation; 
} 

注意的變化:添加參數(第一個索引搜索 - 0將意味着整個陣列搜索像以前一樣)並且i被初始化爲這個新的參數。

(我也改變了max初始值Integer.MIN_VALUE使即使最大值爲負值它的工作,但不應該關心你有原始的問題)

+0

那麼你如何建議我這樣做呢?只需將其較低的範圍添加到當前的最大值? –

+0

我的意思是,我不是在做什麼? –

+0

@NickGatti不,它不是。你沒有更低的範圍,只有陣列。 – kviiri