zoukankan      html  css  js  c++  java
  • 二分法与冒泡排序

    场景 数组 int[] arr=new int[]{1,34,7,5,21}需要快速的找到某个数的下标

    那么我们可以使用二分查找来快速找到这个数的下标,但二分查找数组需要有序且无重复的

    先进行排序,这里我使用的是冒泡排序

    public static void main(String[] args) {
            int[] arr = new int[] { 1, 34, 7, 5,21};
            System.out.println(Arrays.toString(sort(arr)));
        }
    
        //冒泡排序
        public static int[] sort(int[] arr){
            int temp;
            for(int i=0;i<arr.length-1;i++) {//外层控制循环次数
                for (int j = arr.length - 1; j > i; j--) {//内层循环控制每一趟排序的次数
                    if (arr[j - 1] > arr[j]) {
                        temp = arr[j - 1];
                        arr[j - 1] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
            return arr;
        }

    排好序之后就可以使用二分查找了

     public static void main(String[] args) {
            int[] arr = new int[] { 1, 34, 7, 5,21};
            System.out.println(Arrays.toString(sort(arr)));
            System.out.println(search(arr,7));
        }
    
        //冒泡排序
        public static int[] sort(int[] arr){
            int temp;
            for(int i=0;i<arr.length-1;i++) {
                for (int j = arr.length - 1; j > i; j--) {
                    if (arr[j - 1] > arr[j]) {
                        temp = arr[j - 1];
                        arr[j - 1] = arr[j];
                        arr[j] = temp;
                    }
                }
            }
            return arr;
        }
    
        //二分查找
        public static int search(int[] arr, int key) {
            int start=0;
            int end=arr.length-1;
            while(start<=end){
                int middle=(start+end)/2;
                if(key<arr[middle]){
                    end=middle-1;
                }else if(key>arr[middle]){
                    start=middle+1;
                }else {
                    return middle;
                }
            }
            return -1;
        }

  • 相关阅读:
    [Luogu] 封锁阳光大学
    [other] Div
    [USACO11DEC] 牧草种植Grass Planting
    [Luogu] 仓鼠找sugar
    [USACO15DEC]最大流Max Flow
    [noip-2013] 货车运输
    [模板] 普通平衡树
    [Luogu] 树链剖分
    [ZJOI2008] 树的统计Count
    大组合数取模
  • 原文地址:https://www.cnblogs.com/magepi/p/10422824.html
Copyright © 2011-2022 走看看