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

public static int binarySearch(int anArray[], int first, int last, int value) {

ID: 440959 • Letter: P

Question

public static int binarySearch(int anArray[], int first, int last, int value) { /*Searches the array items anArray[first] through anArray[last] for value by using a binary search. Precondition: 0 <= first, last <= SIZE - 1, where anArray[first] <= anArray[first + 1] <= ...<= anArray[last]. Postcondition: If value is in the array, the method returns the index of the array item that equals value; otherwise the method returns -1'.*/ int index; if(first > last) { index = -1; //value not in original array } else { int mid = (first + last)/2; //Invariant: If value is in anArray, anArray[first] <= value <= anArray[last] if(value == anArray[mid]) { index = mid; //value found at anArray[mid] } else if (value < anArray[mid] { index = binarySearch(anArray, first, mid - 1, value); //point X } else { index = binarySearch(anArray, mid + 1, last, value); } } return index; }

Explanation / Answer

import java.util.*; public class BinarySearch { public static void main(String[] args) { int[] intArray = new int[10]; int searchValue = 0, index; System.out.println("Enter 10 numbers"); Scanner input = new Scanner(System.in); for (int i = 0; i