s1.0 二分查詢法
阿新 • • 發佈:2021-12-16
class BinarySearch { /// <summary> /// 查詢方法 /// </summary> /// <param name="nums">資料</param> /// <param name="target">目標值</param> /// <returns></returns> public int search(int[] nums, int target) {int len = nums.Length; int left = 0; int right = len - 1; //目標元素可能存在在區間 [left, right] while (left <= right) { //推薦的寫法是 int mid = left + (right - left) / 2; int mid = (left + right) / 2; if (nums[mid] == target) {return mid; } //如果中間小於目標 else if (nums[mid] < target) { // 目標元素可能存在在區間 [mid + 1, right] left = mid + 1; } //如果中間大於目標 else {// 目標元素可能存在在區間 [left, mid - 1] right = mid - 1; } } return -1; } }
在上圖解: