• Java二分查找


    二分查找思想很简单,也很快,缺点是需要排好序的数,需要结合快速排序使用
    以下是有序数列的二分查找
    n是数字的个数,m是要查找的数字

    import java.util.Scanner;
    
    public class BinarySearch二分查找 {
    
    	public static void main(String[] args) {
    		// TODO Auto-generated method stub
    		Scanner sc=new Scanner(System.in);
    		int n=sc.nextInt();
    		int array[]=new int [n];
    		for(int i=0;i<n;i++) {
    			array[i]=sc.nextInt();
    		}
    		int m=sc.nextInt();
    		int res=binarysearch(array,m,n);
    		System.out.println(res);
    	}
    
    	private static int binarysearch(int[] array, int m,int n) {
    		
    	    int right=0;
    	    int left=n-1;
    	    while(right<=left) {
    	    	int middle=left+right/2;
    	    	if(m==array[middle]) {
    	    		return middle;
    	    	}
    	    	else {
    	    		if(m>array[middle]) {
    	    			right=middle+1;
    	    			
    	    		}else {
    	    			left=middle-1;
    	    		}
    	    	}
    	    	
    	    }
    	    
    		return -1;
    	}
    
    }
  • 相关阅读:
    php 匿名函数和闭包
    项目在线压缩js
    USACOTrainning.The Clocks
    USACOTrainning.Mother's Milk
    c# TXT文件读写
    Access以及少量Regex
    USACOTraining.Packing Rectangles
    First
    CUGBLinker and EXE
    异常处理总结
  • 原文地址:https://www.cnblogs.com/hzcya1995/p/13309691.html
Copyright © 2020-2023  润新知