Back

Binary Search Pseudocode

Inputs: an array A[] with length n, and a target item ‘key’.

      first = 0 
      last = n 
      found = FALSE 

      WHILE first <= last &&	found == FALSE DO 
      BEGIN 
        mid = floor((first + last) / 2) // Find the midpoint of the list. 

        IF A[mid] == key THEN 
          found == TRUE  
        ELSE IF A[mid] > key THEN 
          last = mid – 1 // If the key is smaller than mid, move to the left. 
        ELSE	 
          first = mid + 1 // The key is larger than mid, so go right. 
      END 

      IF found == TRUE THEN 
        output "Found" 
      ELSE 
        output "Not Found"