我使用布尔运算符错了吗?

时间:2016-02-24 11:55:16

标签: c++ algorithm boolean-expression

我正在尝试查看数组以查看是否在其中找到了精确的元素(x)。 为此,我在问题的开头说contor = 0(布尔参数),这意味着数组中没有x,但是如果for循环运行并且在数组中找到x,我说contor = 1 ...并且最后我做了测试if(contor)else并且在数组中找不到x的情况下它不起作用。它只是没有显示任何东西。我不明白......我是初学者。谢谢!

  #include<iostream>

  using namespace std;

  void main()

  {int x, st, dr, m,n,i,contor=0;       //dr = right, st = left, m=middle;
   int v[100];

   cout << "How many elements will the array have?";
   cin >> n;
   cout << endl;

   for (i = 0; i < n;i++)
      {cout << "Insert a element in the array:";
       cin >> v[i];
      }

   cout << "Which is the number you are looking for?";
   cin >> x;

   st = 0;
   dr = n - 1;

   for (i = st; i <= dr;)

      {m = (st + dr) / 2;

      if (v[m] == x)
         { contor = 1;
            break;
         }
      else if (v[m] > x)
          dr = m - 1;
      else st = m + 1;
      }

   if (contor)
       cout << "The element you are looking for is in the array.";
   else
       cout << "The element you are looking for is NOT in the array.";

   cin.get();
   cin.get();
   }

1 个答案:

答案 0 :(得分:3)

您正在尝试进行二分查找,但是您是在无限循环内完成的。如果找到该元素,则会从循环中断开,但如果找不到,则循环会无休止地继续。此外,您尝试在不保证订购的数组中进行二进制搜索。假设数组是有序的,这意味着:

  

i&lt; = j&lt; =&gt; v [i]&lt; = v [j]

这是可行的:

do {
    m = (st + dr) / 2;
    if (v[m] == x) {
        contor = 1;
        break;
    } else if (v[m] > x) {
        dr = (st + m - 1) / 2;
    } else {
        st = (m + dr + 1) / 2;
    }
} while (st < dr);