I am having trouble implementing binary search within my code, can you explain how it works.
binarySearch takes an array of integers a and an integer n and uses
binary search algorithm check if n is contained in a. it returns true if n is
contained in a, as well as printing the number of decision made and false
otherwise.
import java.util.Arrays;
import java.util.Random;
public class Excersice2 {
public static void main(String[] args) {
int[] arr = createArray(10);
System.out.println("the array not sorted");
printArray(arr);
arr = sortArray(arr);
System.out.println("the array sorted");
printArray(arr);
System.out.println(binarySearch(arr,50));
}
public static void printArray(int []arr)
{
System.out.println(Arrays.toString(arr));
}
public static int [] createArray(int n) {
int[] arr = new int[n];
Random rand = new Random();
for(int i = 0; i < n; i++)
arr[i] = rand.nextInt(101);
return arr;
}
public static int[] sortArray(int[] arr) {
Arrays.sort(arr);
return arr;
}
public static boolean binarySearch(int arr[], int n) {
int firstIdx = 0;
int lastIdx = - 1;
int middle = (firstIdx + lastIdx)/2;
int idx = arr.length/2;
while( firstIdx <= lastIdx) {
if(binarySearch[middle] < arr);
}
}
}
The outcomes should look: It took 2 times to find that the value 50 is contained the array. When looking through the list
rand.nextInt. You want to be able to run it in a reproducible way to prove to yourself that you're making progress and fixing bugs. By introducing randomness before you're even confident in your solution, you're making the entire thing much harder for yourself. It also means that we will never be able to reproduce the exact problems that you're experiencing.Randomwith a fixed seed; see the javadocs.binarySearchmethod. You can't debug it unless you have coded it.)