Java-排序 【冒泡排序】

冒泡排序基本的思想是每次比较两个数,大的沉下去,小的冒起来

算法主要是比较相邻的两个元素,如果第一个比第二个大,就交换他们两个。一直从开始的一对比较到最后的一对 ,直到最后

时间复杂度:O(n²)

排序过程如下

代码

package com.niu.demo;

import java.util.Arrays;

/**
 * @description: 冒泡排序
 * @author: nxq email: [email protected]
 * @createDate: 2020/12/21 6:01 下午
 * @updateUser: nxq email: [email protected]
 * @updateDate: 2020/12/21 6:01 下午
 * @updateRemark:
 * @version: 1.0
 **/
public class BubblingSort {
    public static void main(String[] args) {
        int[] arr = {5,6,3,1,8,7,2,4};
        bubblingSort(arr);
        System.out.println(Arrays.toString(arr));
    }

    public static void bubblingSort(int[] arr) {
        if (arr == null || arr.length < 2) {
            return;
        }
        for (int i = 0; i < arr.length - 1; i++) { //对比的次数
            for (int j = 0; j < arr.length - i - 1; j++) {    //每次从哪个位置开始对比
                if (arr[j] > arr[j + 1]) { //如果前一个元素大于后一个元素
                    int temp = arr[j]; //把前一个元素赋值给temp
                    arr[j] = arr[j + 1]; //把后面小的元素赋值给前面的元素
                    arr[j + 1] = temp; // 把大元素的值给后面的小元素
                }
            }
        }

    }
}

最终按照从小到达的方式输出,如果想从大到小排序,把 if (arr[j] > arr[j + 1]) 改为 if (arr[j] < arr[j + 1]) 即可

猜你喜欢

转载自blog.csdn.net/qq_41389354/article/details/111480277
今日推荐