
Concept explainers
Given a sorted array named arr of n elements, write a function to search for a given element x in arr. If the element is present, return the index of x in the array. If the element is not present, return -1. Don't forget that arrays are 0-base-indexed, meaning that the first element in the array is at index 0, and each successive element will be one higher than the one that came before.
Examples:
-
Input: arr = {10, 20, 30, 50, 60, 80, 110, 130, 140, 170}, x = 110
-
Output: 6.
-
Explanation: Element x is present at index 6.
=======================================================================================
Pseudo
How to write a binary search
-
Compare x with the middle element.
-
If x matches with the middle element, we return the mid index.
-
Else If x is greater than the mid element, then x can only lie in the right half subarray after the mid element. So we recur for the right half.
-
Else (x is smaller) recur for the left half.
If the above doesn't get you close enough to the answer, follow along with this in-depth pseudocode. In addition, you're welcome to use online resources to make the algorithm, but make sure you refrain from simply copying and pasting answers. If you don't understand the code that you're using, you won't learn anything.
-
Let min = 0 and max = n-1 where n is the number of elements in the array.
-
Compute guess as the average of max and min, rounded down so that it remains an integer.
-
If array[guess] equals the target, stop. You found it! Return the index of the guess.
-
If the guess was too low, meaning that array[guess] < target, then set min = guess + 1.
-
Otherwise, the guess was too high. Set max = guess - 1. Go back to step 2 and try again.
-
Continue until the value is found, or, if all of the numbers have been checked, return -1 to signal that the algorithm failed to find the number.
In addition, make sure you only edit the method binarySearch(). The parameters have been created for you.
Lastly, make sure to test your code with different values by changing the array and key values.
Test cases:
array = {} // empty array.
// result = -1.
array = {5}, key = 5; // single-element array.
// result = 0.
array = {5}, key = 0; // same as above.
// result = -1.
array = {2, 1}, key = 1; // even number of elements + unsorted.
// result = 0.
array = {5, 1, 4}, key = 4; // odd number of elements + unsorted.
// result = 1.

Step by stepSolved in 2 steps with 4 images

- In JAVA language, find the product of all positive elements present in the array given below and display the product in the output. int []num = {12, -2, 4, 16, -17, 0, 21}; %3Darrow_forward5arrow_forwardpublic int binarySearch(int[]array, int num) {int low = 0;//low rangeint high = array.length -1; //high range int mid; //mid rangewhile () //while low is less than or equal to high{mid = ; //set middle range to be (low + high) /2if () { //if the array in the middle range = input number//return mid range }elseif () { //if the array in the middle range > input number//set the high value to be the mid value minus 1 }else{//set low value to be mid value plus one } }//return -1 here because that would mean that the number is not found in the loop}arrow_forward
- Enhanced selection sort algorithm SelectionSortDemo.java package chapter7; /** This program demonstrates the selectionSort method in the ArrayTools class. */ public class SelectionSortDemo { public static void main(String[] arg) { int[] values = {5, 7, 2, 8, 9, 1}; // Display the unsorted array. System.out.println("The unsorted values are:"); for (int i = 0; i < values.length; i++) System.out.print(values[i] + " "); System.out.println(); // Sort the array. selectionSort(values); // Display the sorted array. System.out.println("The sorted values are:"); for (int i = 0; i < values.length; i++) System.out.print(values[i] + " "); System.out.println(); } /** The selectionSort method performs a selection sort on an int array. The array is sorted in ascending order. @param array The array to sort. */ public static void selectionSort(int[] array) { int startScan, index, minIndex, minValue; for (startScan = 0; startScan < (array.length-1); startScan++) { minIndex = startScan; minValue…arrow_forwardMethod Details getCountInRange public static int getCountInRange(int[] array, int lower, int upper) Returns the number of values in the range defined by lower (inclusive) and upper (inclusive) Parameters: array - integer array lower - lower limit upper - upper limit Returns: Number of values found Throws: java.lang.IllegalArgumentException - if array is null or lower is greater than upper Any error message is fine (e.g., "Invalid parameters(s)")arrow_forwardPython Please **Bold is code** Recap of two-dimensional arrays and their numpy implementation import numpy as np my_2d_array = np.array([[1,2],[3,4],[5,6]]) print("This is my_2d_array:") print(my_2d_array) print("This array has shape " + str(my_2d_array.shape) + " as there are " + str(my_2d_array.shape[0]) + " rows and " + str(my_2d_array.shape[1]) + " columns.") print("The entry of the array with row index " + str(1) + " and column index " + str(1) + " has value " + str(my_2d_array[1,1])) 1) In this problem, implement a TwoDArray class that is meant to mimic (some of) the functionality of a two-dimensional numpy array. DO NOT use numpy at any point. 1A) Give the class an __init__ method Make sure that the variable array is a valid input. This means you should a) Make sure that array is a list of lists. and b) Make sure that each of the inner lists has the same length. You do not need to check for anything else. Rise the appropriate error(s) if these conditions are not met. It is up…arrow_forward
- Computer Networking: A Top-Down Approach (7th Edi...Computer EngineeringISBN:9780133594140Author:James Kurose, Keith RossPublisher:PEARSONComputer Organization and Design MIPS Edition, Fi...Computer EngineeringISBN:9780124077263Author:David A. Patterson, John L. HennessyPublisher:Elsevier ScienceNetwork+ Guide to Networks (MindTap Course List)Computer EngineeringISBN:9781337569330Author:Jill West, Tamara Dean, Jean AndrewsPublisher:Cengage Learning
- Concepts of Database ManagementComputer EngineeringISBN:9781337093422Author:Joy L. Starks, Philip J. Pratt, Mary Z. LastPublisher:Cengage LearningPrelude to ProgrammingComputer EngineeringISBN:9780133750423Author:VENIT, StewartPublisher:Pearson EducationSc Business Data Communications and Networking, T...Computer EngineeringISBN:9781119368830Author:FITZGERALDPublisher:WILEY





