zoukankan      html  css  js  c++  java
  • 经典算法之折半查找

    package 折半查找;
    
    import java.util.Scanner;
    
    public class BinarySearch {
    
    	/**
    	 * 折半查找:要求查找的数据是线性保存,表中的数据是按照从小到大的顺序排列的
    	 */
    	
    	public static int source[] = {6,12,28,37,54,65,69,83,90,92};
    	
    	public static int binarySearch(int s[],int n,int key){
    		int low,high,mid;
    		low = 0;
    		high = n-1;
    		while (low <= high) {
    			mid = (low+high)/2;
    			if (s[mid] == key) {
    				return mid;
    			} else if (s[mid] > key) {
    				high = mid-1;
    			} else {
    				low = mid+1;
    			}
    			
    		}
    		
    		return -1;
    	}
    	public static void main(String[] args) {
    		Scanner input = new Scanner(System.in);
    		System.out.println("请输入关键字");
    		int key = input.nextInt();
    		int pos = binarySearch(source, source.length, key);
    		System.out.println("输出原始数据:");
    		for (int i = 0;i<source.length;i++) {
    			System.out.printf("%d	",source[i]);
    		}
    		System.out.println();
    		
    		if (pos >= 0) {
    			System.out.printf("查找成功,该关键字位于数组的第%d个位置
    ",pos);
    		}else{
    			System.out.println("查找失败!");
    		}
    		
    	}
    	
    	
    	
    	
    	
    	
    	
    	
    }
    
  • 相关阅读:
    @loj
    @codeforces
    @bzoj
    @hdu
    @poj
    @loj
    @bzoj
    @bzoj
    Python配合BeautifulSoup读取网络图片并保存在本地
    Java--多线程读取网络图片并保存在本地
  • 原文地址:https://www.cnblogs.com/airycode/p/5197115.html
Copyright © 2011-2022 走看看