title: Binary Search Using a While Loop (Infinite)
body: <p>I have to implement a Binary Search method using a loop (while). For some weird reason (well, weird for me) the loop keeps going on infinitely, even though certain conditions are met to exit the loop. What am I doing wrong?</p>
  
  <pre><code>public void Bin_search(ArrayList&lt;Integer&gt; arrayList, int targetValue)
  {
    int totalCount = 0;
    int low = 0;
    int high = arrayList.size();
    while (low &lt;= high)
    {
      int mid = low + (high - low) / 2;
      if(targetValue &lt; arrayList.get(mid))
        high = mid - 1;
      else if(targetValue &gt; arrayList.get(mid))
        low = mid + 1;
      else
        totalCount++;
    }
    System.out.println("Number of times "+targetValue+" appears: "+totalCount+" time(s).");
  }
  </code></pre>