冒泡排序把数字“1492586"排序成"9865421"然后生成新的字符串。---苏宁的一道笔试题

public class Bubble {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String initial = "1492586";
        StringBuffer sb = new StringBuffer("");
        int[] array = new int[initial.length()];
        for (int i = 0; i < initial.length(); i++) {
            array[i] = Integer.parseInt(String.valueOf(initial.charAt(i)));
        }
        // System.out.print(Arrays.toString(array));
        for (int i = 0; i < initial.length() - 1; i++) {
            for (int j = 0; j < initial.length() - 1 - i; j++) {
                if (array[j] < array[j + 1]) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
        // System.out.print(Arrays.toString(array));
        for (int i = 0; i < array.length; i++) {
            sb.append(array[i]);
        }
        String out = sb.toString();
        System.out.print(out);
    }

}

运行结果:9865421

 

 

使用ArrayList与Collections

import java.util.ArrayList;
import java.util.Collections;

public class Buble {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        String in = "1492586";
        StringBuffer sbuffer = new StringBuffer("");
        ArrayList<Integer> List = new ArrayList<Integer>();
        for (int i = 0; i < in.length(); i++) {
            List.add(Integer.parseInt(String.valueOf(in.charAt(i))));
        }
        Collections.sort(List);
        Collections.reverse(List);
        System.out.println(List);
        for (int i = 0; i < in.length(); i++) {
            sbuffer.append(List.get(i));
        }
        String out = sbuffer.toString();
        System.out.print(out);
    }

}

运行结果:

[9, 8, 6, 5, 4, 2, 1]
9865421

 

应该还有一些地方可以简化···

 

posted @ 2014-11-06 16:54  从小不打伞  阅读(223)  评论(0编辑  收藏  举报