【数据结构】二分查找及它的演变——插值查找

二分查找关键:mid = (high-low)/2

插值查找演变:mid = low+(high-low)/2

                        需要将1/2变为       ((查找数字-a[mid])/(a[high]-a[low])

package com.chazhao;

import java.util.Arrays;

class shuzu{
	int len,mid,low,high;
	
	public shuzu(){
		
	}
	int a[] = new int[100];
	
	public void create(int []temp){
		System.out.println("创建数组为:");
		System.out.print(a[0]+" ");
		for (int i = 1;i<=10;i++){
			a[i] = temp[i-1];
			System.out.print(a[i]+" ");
		}
		System.out.println();
		
	}
	
	
	public void sort(){
		Arrays.sort(a,0,10);
		System.out.println("排序后为:");
		for (int i = 0;i<len+1;i++){
			System.out.print(a[i]+" ");
		}
		System.out.println();
	}
	
	public void erfen(int key){
		System.out.println("这里是二分查找:");
		low = 1;
		high = len;
		while (low<=high){
			mid  = (low+high)/2;
			if (key<a[mid]){
				System.out.println("此时mid为:"+mid);
				high = mid-1;
				
			}else if (key>a[mid]){
				System.out.println("此时mid为:"+mid);
				low = mid+1;
			}else {
				System.out.println("查找完毕,此时mid为:"+mid);
				return ;
			}
		}
		
	}
	
	public void chazhi(int key){
		System.out.println("这里是插值查找:");
		low = 1;
		high = len;
		while (low<=high){
			mid  = low + (high-low)*(key-a[low])/(a[high]-a[low]);
			//System.out.println(mid);
			if (key<a[mid]){
				System.out.println("此时mid为:"+mid);
				high = mid-1;
				
			}else if (key>a[mid]){
				System.out.println("此时mid为:"+mid);
				low = mid+1;
			}else {
				System.out.println("查找完毕,此时mid为:"+mid);
				return ;
			}
		}
	}
}

public class paixu {
	
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		shuzu px = new shuzu();
		int t[] = {10,20,30,40,50,11,22,33,44,55};
		px.len = 10;
		px.create(t);
		px.sort();
		px.erfen(40);
		px.chazhi(40);

	}

}

                       

 

转载于:https://my.oschina.net/u/3030978/blog/1483980

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值