经典排序算法---冒泡排序

其他的经典排序算法链接地址:https://blog.csdn.net/weixin_43304253/article/details/121209905

1、冒泡排序

基本思想:通过比较相邻数据的大小、将较大的数向后移动。然后再次和后边的数据比较、以此类推、直到将最大的数排到末尾。然后再次循环这个过程、直到完成排序。

1、比较的轮数(2个数需要比较1轮、3个数需要比较2轮、4个数需要比较3(轮)…n个数需要比较(n-1)轮
2、每次轮数需要比较的次数。

比较的轮数:每比较一轮、都会将最大的数据排列到末尾、在下一次比较的过程中就不需要再次比较。也就是说、每比较一轮、下一轮比较的次数就是减少1。每一轮比较的次数也就是 (n-1-i) 【其中i是比较的轮数】
在这里插入图片描述

package com.example.zheng.MyTest;


public class BubbleSort {

    //冒泡排序
    public void bubblSsort(int arr[]) {
        int len = arr.length;

        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 t = arr[j];
                    arr[j] = arr[j + 1];
                    arr[j + 1] = t;
                }

            }
        }
        
    }

    //打印数组
    public void pirnt(int arr[]){
        int len =arr.length;
        for (int i = 0; i < len; i++) {
            System.out.print(arr[i] + " 、");
        }

    }

    public static void main(String[] args) {
        BubbleSort testMy = new BubbleSort();
        
        int[] arr = {1, 3, 2, 5, 4, 6};
        testMy.bubblSsort(arr);
        testMy.pirnt(arr);

    }
}




posted on 2022-08-28 22:19  热爱技术的小郑  阅读(24)  评论(0编辑  收藏  举报