2015-07-03 209 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!谢谢 :) –