zoukankan      html  css  js  c++  java
  • Java数组排序

    一、sort()进行排序

      升序:

    public class Main {
    
        public static void main(String[] args) {
            int[] scores = new int[] {3,1,5,6,4};
            for (int i = 0;i<scores.length;i++){
                System.out.println(scores[i]);
            }
            Arrays.sort(scores);
            for (int j = 0;j<scores.length;j++){
                System.out.println(scores[j]);
            }
    
        }
    }

      降序:

    •   Collections.reverseOrder()方法
    public class Main {
    
        public static void main(String[] args) {
            Integer[] a = {3,4,5,1,2};
            Arrays.sort(a, Collections.reverseOrder());
            for (int i = 0;i<a.length;i++){
                System.out.println(a[i]);
            }
        }
    }
    • 实现 Comparator 接口的复写 compare() 方法
    public class Main {
    
        public static void main(String[] args) {
            Integer[] a = {3,4,5,1,2};
            Comparator cmp = new MyComparator();
            Arrays.sort(a, cmp);
            for (int i = 0;i<a.length;i++){
                System.out.println(a[i]);
            }
        }
    
    }
    class MyComparator implements Comparator<Integer>{
        @Override
        public int compare(Integer o1, Integer o2) {
            return o2 - o1;
        }
    }

    二、冒泡排序

      排序思路:比较数组两个相邻的元素,如果满足条件就交换元素,把较小的元素移至数组前面,较大的元素移至数组后面,这样较大元素会像气泡一样上升至顶部。

     

    public class Demo01 {
        public static void main(String[] args) {
            double[] score = {6,1,5,3,4};
            for (int i = 0; i < score.length - 1; i++) {
                // 比较相邻两个元素,较大的数往后冒泡
                for (int j = 0; j < score.length - 1 - i; j++) {
                    if (score[j] > score[j + 1]) {
                        double temp = score[j + 1]; // 把第一个元素值保存到临时变量中
                        score[j + 1] = score[j]; // 把第二个元素值转移到第一个元素变量中
                        score[j] = temp; // 把临时变量(第一个元素的原值)保存到第二个元素中
                    }
                    System.out.print(score[j] + " "); // 对排序后的数组元素进行输出
                }
                for (int j = score.length - 1 - i; j < score.length; j++) {
                    System.out.print(score[j] + " ");
                }
            }
        }
    }
  • 相关阅读:
    Day 13 匿名函数 :内置函数: 闭包
    Day 12 生成器:生成器表达式:列表表达式:yield:yield from:内置函数
    最近这些天
    正则表达式 I
    Python 软件规范开发
    模块
    常用模块介绍 time datetime os sys hashlib json pickle collections
    模拟博客园登录 基础版
    SQL 必知必会
    Python中的线程和进程
  • 原文地址:https://www.cnblogs.com/wuhao-0206/p/12631396.html
Copyright © 2011-2022 走看看