code kata NO.2 : Karate Chop

二分查找算法实现
本文介绍了一个简单的二分查找算法实现,并通过多个测试用例验证了其正确性。该算法适用于已排序的数组中查找特定元素的位置。

kata2是一个二分查找,很简单,代码如下,已经测试,可以通过所有测试数据

public class MyBinarySearch { static int ind = 0 ; static int chop(int search,int[] array){ int low = 0; int high = array.length-1; while(low <= high){ int mid = low + ((high - low )/2); if (array[mid] == search){ return mid; }else if ( array[mid] < search ){ low = mid+1; }else{ high = mid-1; } } return -1; } static void assert_equal(int i,int j){ if ( i!=j ){ System.out.println("" + ind++ + "error!"); }else{ System.out.println("" + ind++ + "ok!"); } } public static void main(String arg[]){ System.out.println("result:"); assert_equal(0, chop(1, new int[]{1, 3, 5})) ; assert_equal(-1, chop(3, new int[]{1})) ; assert_equal(0, chop(1, new int[]{1})) ; assert_equal(1, chop(3, new int[]{1, 3, 5})) ; assert_equal(2, chop(5, new int[]{1, 3, 5})) ; assert_equal(-1, chop(0, new int[]{1, 3, 5})) ; assert_equal(-1, chop(2, new int[]{1, 3, 5})) ; assert_equal(-1, chop(4, new int[]{1, 3, 5})) ; assert_equal(-1, chop(6, new int[]{1, 3, 5})) ; assert_equal(0, chop(1, new int[]{1, 3, 5, 7})) ; assert_equal(1, chop(3, new int[]{1, 3, 5, 7})) ; assert_equal(2, chop(5, new int[]{1, 3, 5, 7})) ; assert_equal(3, chop(7, new int[]{1, 3, 5, 7})) ; assert_equal(-1, chop(0, new int[]{1, 3, 5, 7})) ; assert_equal(-1, chop(2, new int[]{1, 3, 5, 7})) ; assert_equal(-1, chop(4, new int[]{1, 3, 5, 7})) ; assert_equal(-1, chop(6, new int[]{1, 3, 5, 7})) ; assert_equal(-1, chop(8, new int[]{1, 3, 5, 7})) ; } }

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值