爱吃火腿肠 https://www.cnblogs.com/ichihtc/

  博客园 :: 首页 :: 博问 :: 闪存 :: 新随笔 :: 联系 :: 订阅 订阅 :: 管理 ::
/**
 * @ author ichihtc
 * @ 2022.3.17
 * 冒泡排序法对数组进行排序
 */
public class test8 {
    public static void main(String[] args)
    {
        int[] arr=new int[]{6,4,2,9,3};
        System.out.print("冒泡排序前:");
        printArray(arr);
        bubbleSort(arr);
        System.out.print("冒泡排序后:");
        printArray(arr);
    }
    //输出数组元素
    public static void printArray(int[] arr)
    {
        for(int i=0;i<arr.length;i++)
        {
            System.out.print(arr[i]+" ");
        }
        System.out.print("\n");
    }
    //冒泡排序
    public static void bubbleSort(int[] arr)
    {
        for(int i=0;i<arr.length-1;i++) //只需要执行数组长度-1轮
        {
            for(int j=0;j<arr.length-i-1;j++)
            {
                if(arr[j]>arr[j+1]) //和后面一个数字做判断
                {
                    //和后面一个数字做对换
                    int temp=arr[j];
                    arr[j]=arr[j+1];
                    arr[j+1]=temp;
                }
            }
            System.out.print("第"+(i+1)+"轮排序后:");
            printArray(arr);
        }
    }
}

输出结果:

冒泡排序前:6 4 2 9 3 
第1轮排序后:4 2 6 3 9 
第2轮排序后:2 4 3 6 9 
第3轮排序后:2 3 4 6 9 
第4轮排序后:2 3 4 6 9 
冒泡排序后:2 3 4 6 9 
posted on 2022-03-17 16:29  爱吃火腿肠  阅读(107)  评论(0)    收藏  举报