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})) ; } }