Question: Define a function named BinarySearch that takes two parameters: an array of integers and an integer value to search for: Function BinarySearch() returns the index

Define a function named BinarySearch that takes two parameters: an array of integers and an integer value to search for: Function BinarySearch() returns the index of value to be searched for, or -1 if not found.

Write a main program that reads integers from input. The first integer is the size of an array, the last integer is the value to be searched for, all other integers will be values of the array. Then the program calls function BinarySearch with the array and the value to be searched for as arguments. Function BinarySearch will return the index of the value to be searched for, or -1 if not found.

Ex: if the input is:

8 2 4 7 10 11 32 45 87 10

where 8 is the size of the array, the output is:

Found 10 at index 3

Ex: if the input is:

6 2 4 10 11 32 45 10

where 6 is the size of the array, the output is:

Found 10 at index 2

Ex: if the input is:

7 5 9 11 17 24 30 33 14

where 7 is the size of the array, the output is:

14 was not found

Your program should define and use a function:
Function BinarySearch(integer array(?) numbers, integer key) returns integer found.

  high = numbers.size - 1

  while (high >= low) and (numbers[mid] != key)
     mid = (high + low) / 2
     if numbers[mid] < key
        low = mid + 1
     elseif numbers[mid] > key
        high = mid - 1

  if numbers[mid] != key
     mid = -1

Function Main() returns nothing
  integer array(8) numbers
  integer i
  integer key
  integer keyIndex

  numbers[0] = 2
  numbers[1] = 4
  numbers[2] = 7
  numbers[3] = 10
  numbers[4] = 11
  numbers[5] = 32
  numbers[6] = 45
  numbers[7] = 87

 
  for i = 0; i < numbers.size; i = i + 1
     Put numbers[i] to output
     Put " " to output
  Put "" to output

  key = Get next input
  Put "" to output

  keyIndex = BinarySearch(numbers, key)

  if keyIndex == -1
     Put key to output
     Put " was not found" to output
  else
     Put "Found " to output
     Put key to output
     Put " at index " to output
     Put keyIndex to output


Identify the code and fix it the problems 

Step by Step Solution

3.38 Rating (160 Votes )

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock

It looks like youre trying to implement a binary search func... View full answer

blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!