当前位置:   article > 正文

[算法]二分查找算法

cout<
【思想】

二分搜索主要解决的问题是确定排序后的数组x[0,n-1]中是否包含目标元素target。

二分搜索通过持续跟踪数组中包含元素target的范围(如果target存在数组中的话)来解决问题。

一开始,这个范围是整个数组,然后通过将target与数组中的中间项进行比较并抛弃一半的范围来缩小范围。该过程持续进行,

直到在数组中找到target或确定包含target的范围为空时为止。在有n个元素的表中,二分搜索大约需要执行lgn次比较操作。


提供充足的时间,竟然只有10%的专业程序员能够将这个程序编写正确。

【正解】

  1. /*********************************
  2. * 日期:2015-01-03
  3. * 作者:SJF0115
  4. * 题目: 二分查找算法
  5. * 博客:
  6. **********************************/
  7. #include <iostream>
  8. using namespace std;
  9. int BinarySearch(int A[], int n, int target) {
  10. if(n <= 0){
  11. return -1;
  12. }//if
  13. int start = 0,end = n-1;
  14. // 二分查找
  15. while(start <= end){
  16. // 中间节点
  17. int mid = (start + end) / 2;
  18. // 找到
  19. if(A[mid] == target){
  20. return mid;
  21. }//if
  22. else if(A[mid] > target){
  23. end = mid - 1;
  24. }//else
  25. else{
  26. start = mid + 1;
  27. }//else
  28. }//while
  29. return -1;
  30. }
  31. int main(){
  32. int A[] = {1,2,3,4,7,9,12};
  33. cout<<BinarySearch(A,7,9)<<endl;
  34. return 0;
  35. }
【错解】
  1. /*********************************
  2. * 日期:2015-01-03
  3. * 作者:SJF0115
  4. * 题目: 二分查找算法
  5. * 博客:
  6. **********************************/
  7. #include <iostream>
  8. using namespace std;
  9. int BinarySearch(int A[], int n, int target) {
  10. if(n <= 0){
  11. return -1;
  12. }//if
  13. int start = 0,end = n-1;
  14. // 二分查找
  15. while(start < end){// 错误之处
  16. // 中间节点
  17. int mid = (start + end) / 2;
  18. // 找到
  19. if(A[mid] == target){
  20. return mid;
  21. }//if
  22. else if(A[mid] > target){
  23. end = mid - 1;
  24. }//else
  25. else{
  26. start = mid + 1;
  27. }//else
  28. }//while
  29. return -1;
  30. }
  31. int main(){
  32. int A[] = {1,2,3,4,7,9,12};
  33. cout<<BinarySearch(A,7,3)<<endl;
  34. return 0;
  35. }

错误之处在代码中已经注释。主要原因是你搜索的target正好处于start = end处。例如代码中的例子。

【错解二】
  1. /*********************************
  2. * 日期:2015-01-03
  3. * 作者:SJF0115
  4. * 题目: 二分查找算法
  5. * 博客:
  6. **********************************/
  7. #include <iostream>
  8. using namespace std;
  9. int BinarySearch(int A[], int n, int target) {
  10. if(n <= 0){
  11. return -1;
  12. }//if
  13. int start = 0,end = n-1;
  14. // 二分查找
  15. while(start <= end){
  16. // 中间节点
  17. int mid = (start + end) / 2;
  18. // 找到
  19. if(A[mid] == target){
  20. return mid;
  21. }//if
  22. else if(A[mid] > target){
  23. end = mid; // 可能引起错误之处
  24. }//else
  25. else{
  26. start = mid; // 可能引起错误之处
  27. }//else
  28. }//while
  29. return -1;
  30. }
  31. int main(){
  32. int A[] = {1,2,3,4,7,9,12};
  33. cout<<BinarySearch(A,7,12)<<endl;
  34. return 0;
  35. }










声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/正经夜光杯/article/detail/977559
推荐阅读
相关标签