Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

IN JAVA, Please write code that would implement the following pseudocode for a b

ID: 3575995 • Letter: I

Question

IN JAVA,

Please write code that would implement the following pseudocode for a binary search algorithm (assume main method already exists).

Program 9.7 (not a complete program) 1 The binarysearch function accepts as arguments an Integer 2 array, a value to search the array for and the size 3 of the array. If the value is found in the array, its 4 subscript is returned. Otherwise -1 is returned, 5 indicating that the value was not found in the array. 6 Function Integer binarysearch (Integer array[ Integer value Integer arraysize) Variable to hold the subscript of the first element 9 Declare Integer first 0 10 variable to hold the subscript of the last element 11 12 Declare Integer last arraysize 1 13 Position of the search value 15 Declare Integer position -1 16 Flag 17 Declare Boolean found False 18 19 Variable to hold the subscript of the midpoint 20 21 Declare Integer middle 22 While (NOT found) AND (first last) 23 Calculate the midpoint 24 Set middle (first last) 2 25 26 See if the value is found at the midpoint. 27 If array[middle] 28 value Then Set found True 29 Set position. middle 30 31 Else, if the value is in the lower half 32 33 Else If array[middle] value Then 34 Set last middle 1 35 Else, if the value is in the upper half 36 Else 37 Set first middle 1 38 39 End If 40 End While 41 Return the position of the item, or -1 42 if the item was not found 43 Return position 44 45 End Function

Explanation / Answer

Hi, Please find my implementation.

Please let me know in case of any issue.

public class BinarySearch {

   public static int binarySearch(int array[], int value, int arraySize){

       int first = 0;

       int last = arraySize -1;

       int position = -1;

       Boolean found = false;

       int middle;

       while((!found) && first <= last){

           middle = (first+last)/2;

           if(array[middle] == value){

               found = true;

               position = middle;

           }

           else if(array[middle] > value){

               last = middle-1;

           }

           else{

               first = middle+1;

           }

       }

       return position;

   }

   public static void main(String[] args) {

      

       int[] arr = {43,67,89,98,112,432,567,890};

      

       int key = 112;

      

       System.out.println(binarySearch(arr, key, arr.length));

   }

}