Suggested Solution

Task 1 Task 2 Task 3

Task 1

Without looking back at the unit page, can you complete this algorithm written in pseudocode?!

Binary Search Algorithm

Let's say a global variable which is an array stores sorted values.

A function, BinarySearch, searches the array for an item.

If it finds the item, it returns its index. Otherwise, it returns -1.

Note:lowerBound is the smallest index of the array and upperBound is the largest index of the array...

Complete the function below.

pre-condition: arr is already in ascending order of value

function BinarySearch([ ] arr, item )

lowerBound =

= length(arr)-1

middle = ()/2

loop while arr[middle] != item and lowerBound <= upperBound

if arr[middle] = then

return middle

else if item < arr[middle] then

upperBound =

else

lowerBound =

end if

middle = (lowerBound+upperBound)/2

end loop

end function

 

SUBMIT a screenshot of your solution.

Task 2

A program processes a 2D array of doubles row by row. It counts how many of the rows contain a particular item. Here is an attempt at the code:

Code the sortRow and binarySearch functions so that the program works as intended.

Random Name

Task 3

Here is an alternative algorithm for binary search. It uses exactly the same technique of halving the problem with each iteration of the loop:

function anotherBinarySearch(intArray, targetItem){

lb = 0

ub = length(intArray)-1

loop while lb <= ub

mid = (lb+ub)/2

if intArray[mid] = target then

return mid

else

if target > intArray[mid] then

lb = mid + 1

else

ub = mid - 1

end if

end if

end loop

end function

Code this function in the high-level language you are studying.

Test your design by writing a driver/main function and check that it works as expected.