今天同事在车上和我说面试,有道这题目,他没做出来
private static void testsearch(int searchvalue){ int[] array= {1, 2, 3, 4, 5}; int max = array.length; int min = 0; int mid = (max + min) /2; while(min <= max ){ if (searchvalue == array[mid]){ System.out.println("find index " + mid); break; }else if (searchvalue > array[mid]) min = mid + 1; else max = mid -1; mid = (max + min) /2; } } 调用 testsearch(5);
到公司自己简单写了写。