Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>You have some fundamental errors in your code:</p> <p>Code issues:</p> <pre><code> else if (A[mid] &lt; value){ cout&lt;&lt; A[mid] &lt;&lt; " &lt; " &lt;&lt; value &lt;&lt;endl; return BinarySearch(A, value, mid+1, high, count); } if (A[mid] == value){ //^^^^another else is missing cout&lt;&lt; A[mid] &lt;&lt; " = " &lt;&lt; value &lt;&lt;endl; count = count + 1; } </code></pre> <p>Meanwhile, The way you are trying to use binary search to find the occurrence of a given number is not quite right. It should be done as follows:</p> <p>since you already sorted the array with insertion sort. What you need to do is the simply using binary search to find the first and last occurrence of the given integer, then the total number of occurrence is simple arithmetic between those two indices. </p> <p>For example, given array (sorted) as follows:</p> <pre><code> 1 2 3 4 4 4 4 4 5 5 5 </code></pre> <p>you would like to find 4, then you use binary search to find first appearance at index 3 and last appearance at index 7, the total number of appearance is then 7-3 +1 = 5.</p> <p>The major code should be something like the following:</p> <pre><code>int findFrequency(int A[], int x, int n) { int firstIndex = findFirst(A, 0, n-1, x, n); if(firstIndex == -1) return firstIndex; //only search from firstIndex to end of array int lastIndex = findLast(A, firstIndex, n-1, x, n); return (lastIndex - firstIndex + 1); } int findFirst(int A[], int low, int high, int x, int n) { if(high &gt;= low) { int mid = low + (high - low)/2; if( ( mid == 0 || x &gt; A[mid-1]) &amp;&amp; A[mid] == x) return mid; else if(x &gt; A[mid]) return findFirst(arr, (mid + 1), high, x, n); else return findFirst(A, low, (mid -1), x, n); } return -1; } int findLast(int A[], int low, int high, int x, int n) { if(high &gt;= low) { int mid = low + (high - low)/2; if( ( mid == n-1 || x &lt; A[mid+1]) &amp;&amp; A[mid] == x ) return mid; else if(x &lt; A[mid]) return findLast(A, low, (mid -1), x, n); else return findLast(A, (mid + 1), high, x, n); } return -1; } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload