2015-07-03 260 views
2

所以我現在有這個代碼。它運行,但它不會按升序對數組排序,我不知道該怎麼辦。我是新來的java所以...按升序對數組進行排序

import javax.swing.JOptionPane; 

public class ThirdClass 
{ 
    public static void main (String args[]){ 

     int a = 0; 
     int b; 

     int numbers; 
     int length = Integer.parseInt(JOptionPane.showInputDialog (null, "Input set size", JOptionPane.QUESTION_MESSAGE)); 
     int ctr = 1; 
     int num[] = new int[length]; 

      for(int i = 0; i < length; i++){ 
      num[i] = Integer.parseInt(JOptionPane.showInputDialog (null, "Enter number " + ctr, JOptionPane.QUESTION_MESSAGE)); 
        ctr++; 
      } 

      for(int i = 0; i < length; i++){ 
       for(int j = i+1; j < length; j++){ 
         if(num[i]<num[j]){ 
          a = num[i]; 
          num[i] = num[j]; 
          num[j] = a; 
         } 
        } 
      } 

      for(int i = 0; i < length; i++){ 
      JOptionPane.showMessageDialog (null, "Output: " + num[i] , "Value", JOptionPane.INFORMATION_MESSAGE); 
      } 
    } 
} 

回答

3

你似乎試圖做一個冒泡排序,但你的邏輯是有點關閉。將您的雙重for環路更改爲:

for (int i=0; i < length; ++i) { 
    for (int j=1; j < (length-i); ++j) { 
     if (num[j-1] > num[j]){ 
      a = num[j-1]; 
      num[j-1] = num[j]; 
      num[j] = a; 
     } 
    } 
} 
+0

我會試試這個。謝謝! –

2

您無需更改完整的邏輯。只需要將符號更改爲大於 請檢查以下代碼。

for(int i = 0; i < length; i++){ 
       for(int j = i+1; j < length; j++){ 
         if(num[i]>num[j]){ 
          a = num[i]; 
          num[i] = num[j]; 
          num[j] = a; 
         } 
        } 
      } 
+0

This works too!謝謝 :) –