zoukankan      html  css  js  c++  java
  • 冒泡排序和二分查找算法

    1.冒泡排序:

        

        private static void bubbleSort(int[] arr) {
            for(int j=0;j<arr.length-1;j++){  //外层循环 控制排序的次数
                for(int m=0;m<arr.length-1-j;m++){  //内层循环 控制每一趟排序多少次
                        if(arr[m]>arr[m+1]){
                            int temp = arr[m];
                            arr[m] = arr[m+1];
                            arr[m+1] = temp;
                        }
                }
            }
        }

    2.二分查找

      二分查找算法分为循环查找和递归查找

      01.循环查找

       

     /**
         *
         * @param arr 数组
         * @param x  查找值
         * @return   查到的值
         */
    
        public static int binarySearch(int[] arr, int x) {
    
            int low= 0;
            int high = arr.length-1;
    
            while (low <= high){
                int middle = (low+high)/2;
                if(x==arr[middle]){
                    return arr[middle];
                }else if(x < arr[middle]){
                    high = middle - 1;
                }else if(x > arr[middle]){
                    low = middle + 1;
                }
    
    
            }
            return -1;
        }

    02.递归查找

      

    /**
         * 递归查找
         * @param arr  数组
         * @param key  需要查询的值
         * @param start 开始上标
         * @param end   开始下标
         * @return  找到的值
         */
        public static int binarySearch(int[] arr,int key,int start,int end){
    
            if(start>end||start<0){
                return -1;
            }else{
    
                int middle = (start+end)/2;
    
                if(key == arr[middle]){
                    return key;
                }
    
                if(key < arr[middle]){
                    return  binarySearch(arr,key,start,middle-1);
                }
    
                if(key>arr[middle]){
                    return  binarySearch(arr,key,middle+1,end);
                }
    
                return -1;
    
            }
        }

    测试:

      

     public static void main(String[] args) {
            int[] arr = { 6, 12, 33, 87, 90, 97, 108, 561 };
            System.out.println("循环查找:" + binarySearch(arr, 87));
            System.out.println("递归查找:"+binarySearch(arr,87,0,arr.length-1));
        }

    输出结果:

    循环查找:87
    递归查找:87
    
    Process finished with exit code 0
    

      

     

  • 相关阅读:
    有关WCSF的几点整理
    应用Response.Write实现带有进度条的多文件上传
    使用Response.Write实现在页面的生命周期中前后台的交互
    多线程实现Thread.Start()与ThreadPool.QueueUserWorkItem两种方式对比
    LinQ to SQL 及 non-LinQ方式实现Group的Performance对比
    Object.assign()方法
    继承
    面对对象和原型链
    画布实现验证码
    日期的格式 字符串转日期
  • 原文地址:https://www.cnblogs.com/liutianci/p/10329932.html
Copyright © 2011-2022 走看看