今天去一家公司去面试,给我三道题目,第二道题目给难到了,思路都懂,就是一下子思路闭塞了,哎,,
还是多写点程序啊,不能只看框架之类的,基础还是很重要的
二分查找算法 备份一下
public static int binSearch(int srcArray[], int key) { int mid = srcArray.length / 2; if (key == srcArray[mid]) { return mid; } int start = 0; int end = srcArray.length - 1; while (start <= end) { mid = (end - start) / 2 + start; if (key < srcArray[mid]) { end = mid - 1; } else if (key > srcArray[mid]) { start = mid + 1; } else { return mid; } } return -1; }
运用递归的二分查找算法
public static int binSearch(int srcArray[], int start, int end, int key) { int mid = (end - start) / 2 + start; if (srcArray[mid] == key) { return mid; } if (start >= end) { return -1; } else if (key > srcArray[mid]) { return binSearch(srcArray, mid + 1, end, key); } else if (key < srcArray[mid]) { return binSearch(srcArray, start, mid - 1, key); } return -1; }