冒泡排序.

冒泡排序.,第1张

冒泡排序
  • 冒泡的代码,两层循环,外层冒泡轮数,里层依次比较

  • 我们看到嵌套循环,应该立马就可以得出这个算法的时间复杂度为O(n2)

    package com.array;
    ​
    import java.util.Arrays;
    ​
    public class ArrayDemo08 {
        public static void main(String[] args) {
            int[] arrays = {5,8,9,7,6,115,7897,46,4,8798};
            System.out.println(Arrays.toString(sort(arrays)));
    ​
        }
    ​
        public static int[] sort(int[] arrays) {
            int temp = 0;
            //外层循环,判短我们这个要走多少次
            for (int i = 0; i < arrays.length; i++) {
                //内层循环,比较判断两个数,如果第一个数,比第二个数大,则交换位置
                for (int j = 0; j < arrays.length - 1-i; j++) {
                    if (arrays[j] < arrays[j + 1]) {
                        temp = arrays[j];
                        arrays[j] = arrays[j + 1];
                        arrays[j + 1]=temp;
                    }
    ​
                }
    ​
            }
            return arrays;
        }
    }

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/795353.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-06
下一篇2022-05-06

发表评论

登录后才能评论

评论列表(0条)

    保存