zoukankan      html  css  js  c++  java
  • 冒泡排序及优化

    1.冒泡排序:

          实现思想:相邻的两个元素比较,反序就交换.

          时间复杂度:O(n2)

    public static void main(String[] args) {
            int[]arr={33,5,8,9,7,6,3,1,2,4,45};
            bubbleSort(arr);
            for(int i:arr){
                System.out.print(i+",");
            }
        }
        public static void bubbleSort(int[]arr){
            for(int i=0;i<arr.length-1;i++){
                for(int j=arr.length-1;j>i;j--){
                    if(arr[j]<arr[j-1]){
                        int a=arr[j];
                        arr[j]=arr[j-1];
                        arr[j-1]=a;
                    }
                }
            }
        }

    2.冒泡排序的优化:设置一个标志位.避免有序情况下的没必要循环

    public static void main(String[] args) {
            int[]arr={33,5,8,9,7,6,3,1,2,4,45};
            bubbleSort2(arr);
            for(int i:arr){
                System.out.print(i+",");
            }
        }
        public static void bubbleSort2(int[]arr){
            boolean flag=true;
            for(int i=0;i<arr.length-1&&flag;i++){
                flag=false;
                for(int j=arr.length-1;j>i;j--){
                    if(arr[j]<arr[j-1]){
                        int a=arr[j];
                        arr[j]=arr[j-1];
                        arr[j-1]=a;
                        flag=true;
                    }
                }
                
            }
            
        }

  • 相关阅读:
    Python 面向对象(下)
    Python 面向对象(上)
    《面向对象程序设计概述》 牛咏梅
    lastIndexOf is not a function
    oracle lpad 函数使用介绍
    oracle中length、lengthb、substr、substrb用法小结
    oracle获取字符串长度函数length()和hengthb()
    js获取当前日期时间
    win7系统下查看端口的占用情况以及如何删除端口进程
    IntelliJ IDEA “Finds duplicated code”提示如何关闭
  • 原文地址:https://www.cnblogs.com/2nao/p/6427087.html
Copyright © 2011-2022 走看看