首页 > 代码库 > 查找算法
查找算法
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)); } }
查找算法
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。