Please explain each line of code of what the code is doing, thank you :-) import
ID: 3885346 • Letter: P
Question
Please explain each line of code of what the code is doing, thank you :-)
import edu.princeton.cs.introcs.In: import edu.princeton.cs.introcs.StdIn: import edu.princeton.cs.introcs.StdOut: import java.util.Arrays: public class BinarySearch { // return the index of the key in the sorted array a[]: -1 if not found public static int search(String key, String[] a) { return search(key, a, 0, a.length): } public static int search(String key, String[] a, int lo, int hi) { // possible key indices in [lo, hi) if (hi 0) return search(key, a, lo, mid): else if (cmpExplanation / Answer
Main function :
First block
Input is read in s as a single line from command line argument in the form of args[]
Then the words are separated out in the array words using the split funciton
Second block
The words array is sorted using in built sort function in java
Third Block
Now the user is asked for a string as input
which acts as key to be searched in the array words[] using the search function
Search function with 2 parameters :
It is just a supporting function to initiate the binary search function
Search function with 4 parameters :
It uses binary search to find the index of the given key in the sorted list/array of words
In this search function there are 4 parameters :
Lo : we can expect key to definitely lie above this index
Hi : we can expect key to definitely lie under this index
mid is the avg of lo and hi to give us a reference of the search space
we will compare the string at mid index to the key and decide accordingly
The cmp(s1,s2) function returns 1 if s1 > 2 , returns 0 if s1 = s2 and -1 otherwise
Case 1 a[mid] > key means that key is lexicographically smaller than mid index string so we need to only search in range 0 to mid
case 2 a[mid] < key means that key is lexicogrraphically larger than mid index string so we need to only search in range mid+1 to hi
case 3 a[mid] = key means that key is equal to a[mid] so this is the index that needs to be returned