首页 > 编程语言 > 详细

【苏宁易购笔试题】冒泡排序把数字“1492586"排序成"9865421"然后生成新的字符串。

时间:2014-11-06 19:32:05      阅读:322      评论:0      收藏:0      [点我收藏+]
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

 

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

 

【苏宁易购笔试题】冒泡排序把数字“1492586"排序成"9865421"然后生成新的字符串。

原文:http://www.cnblogs.com/maple42/p/4079326.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!