首页 > 代码库 > Summary: Binary Search
Summary: Binary Search
Iterative ways:
1 int binarySearch (int[] a, int x) { 2 int low = 0; 3 int high = a.length - 1; 4 int mid; 5 6 while (low <= high) { 7 mid = (low + high) / 2; 8 if (a[mid] < x) { 9 low = mid + 1;10 } 11 else if (a[mid] > x) {12 high = mid - 1;13 }14 else {15 return mid;16 } 17 } 18 return -1;19 }
Recursive ways:
1 int binarySearchRecursive (int[] a, int x, int low, int high) { 2 if (low > high) return -1; //error 3 4 int mid = (low + high) / 2; 5 if (a[mid] < x) { 6 return binarySearchRecursive(a, x, mid + 1, high); 7 } 8 else if (a[mid] > x) { 9 return binarySearchRecursive(a, x, low, mid - 1);10 }11 else {12 return mid;13 }14 }
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。