赞
踩
package Basic; public class BinarySearch{ public static int binarySearchBasic(int a[],int target) { int i=0,j=a.length-1; while(i<=j) { //注意这里的判断条件 int m=(i+j)>>>1; //注意不能直接用除法 if(target==a[m]) { return m; } else if(target<a[m]) { j=m-1; } else if(a[m]<target) { i=m+1; } } return -1; } }
测试代码如下:
package Basic; import org.junit.Assert; import org.junit.jupiter.api.DisplayName; import org.junit.jupiter.api.Test; import Basic.BinarySearch.*; import static Basic.BinarySearch.binarySearchBasic; public class TestBinarySearch { @Test @DisplayName("binarySearchBasic 找到目标值") public void test1(){ int[] a={7,9,11,17,19,23,34};//升序排列的数组 //断言测试 Assert.assertEquals(0,binarySearchBasic(a,7)); Assert.assertEquals(1,binarySearchBasic(a,9)); Assert.assertEquals(2,binarySearchBasic(a,11)); Assert.assertEquals(3,binarySearchBasic(a,17)); Assert.assertEquals(4,binarySearchBasic(a,19)); Assert.assertEquals(5,binarySearchBasic(a,23)); Assert.assertEquals(6,binarySearchBasic(a,34)); } @Test @DisplayName("binarySearchBasic 没找到目标值") public void test2(){ int[] a={7,9,11,17,19,23,34};//升序排列的数组 //断言测试 Assert.assertEquals(-1,binarySearchBasic(a,8)); Assert.assertEquals(-1,binarySearchBasic(a,13)); Assert.assertEquals(-1,binarySearchBasic(a,20)); } }
之前i和j是闭合区间,i和j都需要参加比较,二分查找还有另一种版本,就是左闭右开区间,j不参与比较,在原版的基础上做了三处改动
改动的原理都是因为j不参与比较,只判断[i,j)之间的值,如果[i,j)之间没有值了则查找失败
package Basic; public class BinarySearch{ public static int binarySearchBasic(int a[],int target) { //int i=0,j=a.length-1; int i=0,j=a.length; //while(i<=j) { while(i<j) { int m=(i+j)>>>1; if(target==a[m]) { return m; } else if(target<a[m]) { //j=m-1; j=m; } else if(a[m]<target) { i=m+1; } } return -1; } }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。