Question: Binary Search- I will need you to comment or trace on each line of the code. Be specific what does each code do or mean

Binary Search- I will need you to comment or trace on each line of the code. Be specific what does each code do or mean and why? This code was in java, thank you!

public class IntegerList

{

int[] list; //values in the list

//-------------------------------------------------------

//create a list of the given size

//-------------------------------------------------------

public IntegerList(int size)

{

list = new int[size];

}

//-------------------------------------------------------

//fill array with integers between 1 and 10, inclusive

//-------------------------------------------------------

public void randomize()

{

for (int i=0; i

list[i] = (int)(Math.random() * 10) + 1;

}

//-------------------------------------------------------

//print array elements with indices

//-------------------------------------------------------

public void print()

{

for (int i=0; i

System.out.println(i + ":\t" + list[i]);

}

//-------------------------------------------------------

//sorts array elements

//-------------------------------------------------------

public void sort()

{

int min, temp;

for (int i=0; i

{

min=i; //sets min to current outer loop index

for(int test=i+1;test

if(list[test]

min=test;

//swap the values

temp = list[min];

list[min] = list[i];

list[i] = temp;

}

}

//-------------------------------------------------------

//return the index of the first occurrence of target in the list.

//return -1 if target does not appear in the list

//-------------------------------------------------------

public int binarySearch(int target)

{

int low = 0;

int high - list.length-1;

int middle = (low + high)/2;

While (list[middle] != target && low <= high)

{

if(target < list[middle])

high = middle -1;

else

low = middle +1;

middle = (low + high) /2;

}

if(list[middle] == target)

return middle;

else return -1;

}

public class Tester

{

public static void main(String args[])

{

IntegerList list = new IntegerList(5);

list.randomize();

list.sort();

list.binarySearch(8);

list.print();

System.out.println("Search for the value 8");

if(list.binarySearch(8) == -1)

System.out.println("You didn't find the value 8");

else

System.out.println("Congrats, 8 is found");

}

}

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!