Java算法2--二分搜索法
来源:互联网 发布:js怎么获取毫秒数 编辑:程序博客网 时间:2024/06/04 06:52
一、二分搜索法实现类
public class BinarySearch { public static int BinarySearch1(int a[],int x,int n) { int left=0;int right=n-1; while(left<=right) { int middle=(left+right)/2; if(x==a[middle]) return middle; if(x>a[middle]) left=middle+1; else right=middle-1; } return -1; }} public static int BinarySearch2(int a[],int x,int n) { int left=0;int right=n-1; while(left<right-1) { int middle=(left+right)/2; if(x<a[middle]) right=middle; else left=middle; } if(x==a[left]) return left; return -1; } public static int BinarySearch3(int a[],int x,int n) { int left=0;int right=n-1; while(left+1!=right) { int middle=(left+right)/2; if(x>=a[middle]) left=middle; else right=middle; } if(x==a[left]) return left; return -1; } public static int BinarySearch4(int a[],int x,int n) { if(n>0&&x>=a[0]) { int left=0;int right=n-1; while(left<right) { int middle=(left+right)/2; if(x<a[middle]) right=middle-1; else left=middle; } if(x==a[left]) return left; } return -1; } public static int BinarySearch5(int a[],int x,int n) { if(n>0&&x>=a[0]) { int left=0;int right=n-1; while(left<right) { int middle=(left+right+1)/2; if(x<a[middle]) right=middle-1; else left=middle; } if(x==a[left]) return left; } return -1; } public static int BinarySearch6(int a[],int x,int n) { if(n>0&&x>=a[0]) { int left=0;int right=n-1; while(left<right) { int middle=(left+right+1)/2; if(x<a[middle]) right=middle-1; else left=middle+1; } if(x==a[left]) return left; } return -1; } public static int BinarySearch7(int a[],int x,int n) { if(n>0&&x>=a[0]) { int left=0;int right=n-1; while(left<right) { int middle=(left+right+1)/2; if(x<a[middle]) right=middle; else left=middle; } if(x==a[left]) return left; } return -1; }}
二、二分搜索法测试类
public class BinarySearchTest { public static void main(String agrs[]) { int[] a=new int[]{5,17,21,45,69,84,105}; //System.out.print(BinarySearch.BinarySearch1(a,5,a.length)); //System.out.print(BinarySearch.BinarySearch1(a,105,a.length)); //System.out.print(BinarySearch.BinarySearch1(a,3,a.length)); //System.out.print(BinarySearch.BinarySearch1(a,120,a.length)); //System.out.print(BinarySearch.BinarySearch1(a,17,a.length)); }}
1 0
- Java算法2--二分搜索法
- java二分搜索算法
- 二分查找算法(java)二分搜索
- java 二分搜索法
- (基于Java)算法之二分搜索法
- 分治:二分搜索法算法的java实现
- 算法之二分搜索法
- 二分搜索算法(JAVA Code)
- 【基础算法】搜索-二分搜索
- 搜索算法之二分查找法
- 查找算法(二)二分搜索法
- C#二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 二分搜索算法
- 简单算法--二分搜索
- ATL的GUI程序设计(4)
- Android 6.0运行时权限处理
- 随机森林与Adaboost
- 第五周 项目1 圆的周长
- 第五周用raptor计算圆的周长
- Java算法2--二分搜索法
- 死锁
- WebServices 简单安全验证以及调用频率限制
- Naive Bayes
- Raptor1
- K-means
- EM算法与GMM
- 求值
- JAVA开发环境安装及配置