算法 30

作者: holmes000 | 来源:发表于2020-04-19 22:14 被阅读0次

查找和排序

题目:输入任意(用户,成绩)序列,可以获得成绩从高到低或从低到高的排列,相同成绩
都按先录入排列在前的规则处理。

示例:
jack 70
peter 96
Tom 70
smith 67

从高到低 成绩
peter 96
jack 70
Tom 70
smith 67

public static void main(String[] args) {
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        try {
            String str;
            while ((str = bufferedReader.readLine()) != null) {
                Integer size = Integer.valueOf(str);
                //0 DESC 1ASC
                Integer sortMethod = Integer.valueOf(bufferedReader.readLine());
                //用户名称
                String[] names = new String[size];
                //分数
                Integer[] scores = new Integer[size];
                for (int i = 0; i < size; i++) {
                    String[] strings = bufferedReader.readLine().split(" ");
                    names[i] = strings[0];
                    scores[i] = Integer.valueOf(strings[1]);
                }
                if (sortMethod.equals(0)) {
                    insertSortDesc(names, scores);
                    Arrays.sort(scores,Comparator.reverseOrder());
                }
                if (sortMethod.equals(1)) {
                    insertSortAsc(names, scores);
                }
                for (int i = 0; i < scores.length; i++) {
                    System.out.println(names[i] + " " + scores[i]);
                }
                break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void insertSortAsc(String[] names, Integer[] scores) {
        if (names == null || names.length < 2) {
            return;
        }
        if (scores == null || scores.length < 2) {
            return;
        }
        // 0~0 有序的
        // 0~i 想有序
        for (int i = 1; i < scores.length; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (scores[j] > scores[j + 1]) {
                    swap(scores, j, j + 1);
                    swap(names, j, j + 1);
                }
            }
        }
    }

    private static void insertSortDesc(String[] names, Integer[] scores) {
        // 0~0 有序的
        // 0~i 想有序
        for (int i = 1; i < scores.length; i++) {
            for (int j = i - 1; j >= 0; j--) {
                if (scores[j] < scores[j + 1]) {
                    swap(scores, j, j + 1);
                    swap(names, j, j + 1);
                }
            }
        }
    }

    private static void swap(Object[] str, Integer i, Integer j) {
        Object tmp = str[i];
        str[i] = str[j];
        str[j] = tmp;
        //当是int可以使用异或运算
//        str[i] = str[i] ^ str[j];
//        str[j] = str[i] ^ str[j];
//        str[i] = str[i] ^ str[j];
    }

相关文章

网友评论

      本文标题:算法 30

      本文链接:https://www.haomeiwen.com/subject/qrdwbhtx.html