码迷,mamicode.com
首页 > 编程语言 > 详细

查找算法

时间:2015-01-30 10:43:28      阅读:291      评论:0      收藏:0      [点我收藏+]

标签:算法   分块查找   二分查找   

1.二分查找

package com.spring.test;

/**
 * Created by brady on 15-1-28.
 */
public class Bi {
    public static int f(int[] a, int l){
        int p =0;
        int left = 0;
        int right = a.length;
        while (left<=right){
            int middle = (left + right)/2;
            if(a[middle]<l) left = middle+1;
            else if(a[middle]>l) right = middle-1;
            else return middle;
        }

        return -1;
    }

    public static void main(String[] args){
        int[] a = new int[]{1,3,5,6,6,9};
        System.out.println(f(a,3));
    }
}

2.分块查找

package com.spring.test;

/**
 * Created by brady on 15-1-28.
 */
public class Ku {

    /*
     * a为索引数组
     * b为实际数组
     * key是要查找的键值
     * length是块的长度
     *
     */
    public static int f(int[] a, int[] b, int key,int length){
        if(a.length<=0){
            return -1;
        }
        int left=0;
        int right=a.length;
        while (left<=right){
            int middle=(left+right)/2;
            if(a[middle]>key) right=middle-1;
            else if(a[middle]<=key) left=middle+1;
        }

        for(int i=left*length;i<left*length+length;i++){
            if(b[i]==key) return i;
        }
        return -1;
    }

    public static void main(String[] args){
        int[] a = new int[]{5,7,19};
        int[] b = new int[]{1,2,4,5,3,5,3,7,3,8,6,19};
        System.out.println(f(a,b,8,4));
    }

}


查找算法

标签:算法   分块查找   二分查找   

原文地址:http://blog.csdn.net/yaoqinggg/article/details/43233143

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!