我怎么能按降序排列?请建议

时间:2015-03-12 03:14:30

标签: java

我正在尝试编写一个用户提供输入的程序,输出应按降序排列,使字符串保持相同的位置。例如:如果输入为3,则p,11,...,4,#输出应为11,p,4,。,3,#。我试过这个。

String input = JOptionPane.showInputDialog("Enter a string:");
String[] abc = input.split(",");
ArrayList<Integer> num = new ArrayList<Integer>();
for (int i = 0; i < abc.length; i++) {
 num.add(Integer.parseInt(abc[i]));
 for ( int z = 0; z < num.size() - 1; z ++ ) {
 int numI;
  try { numI = Integer.parseInt( num.get(z)); 
  }
 catch (NumberFormatException nfe) { continue; }
 for (int j = z + 1; j < num.size(); j ++ ){
 int numJ;
 try { numJ = Integer.parseInt(num.get(z));
 } 
 catch (NumberFormatException nfe) { continue; }
 if (numI < numJ) {
 Integer temp = num.get(z);//swapping
 num.put(z, num.get(j));
 num.put(j, temp);   
 }

 }

有什么问题?请建议

1 个答案:

答案 0 :(得分:0)

以下是基于冒泡排序的简单解决方案:

public static void main(final String[] args) {

        final String input = args[0];

        final String[] tokens = input.split(",");

        for (int i = 0 ; i < tokens.length ; i++) {
            for (int j = i + 1 ; j < tokens.length ; j++) {
                String left = tokens[i];
                String right = tokens[j];
                if (isNumber(left) && isNumber(right)) {
                    int lNum = Integer.valueOf(left);
                    int rNum = Integer.valueOf(right);
                    if (lNum < rNum) {
                        swap(tokens, i, j);
                    }
                }
            }
        }

     }

    private static boolean isNumber(String s) {
        try {
            Integer.parseInt(s);
            return true;
        }
        catch (NumberFormatException nfe) {
            return false;
        }
    }

    private static void swap(final String[] arr, int i, int j) {
        final String tmp = arr[i];
        arr[i] = arr[j];
        arr[j] = tmp;
    }