The goal of this project is to create a class search. I will need methods of binary search and linear search. For each method you are going to ask the user for a key, then search for this key in an array of numbers (you can assume the numbers in the array). If you found the key return its location, otherwise returns -1. Test these methods by creating an object from the Search class (in the main method) and calling the linear and the binary methods.
Below I have created the code and I am trying to create my main so I can test the linear and binary methods but it is not working. It could be because I'm testing like three different classes in the same main, but I am not sure I formatted them in the right way and that's the reason why I am getting errors. I need help, please.
My Search class.
`
public class Search {
public static int linearsearch(int arr2[], int x2) {
int N = arr2.length;
for (int i = 0; i < N; i++) {
if (arr2[i] == x2)
return i;
}
return -1;
}
public int binarySearch(int arr3[], int l, int r, int x) {
if (r >= l) {
int mid = l + (r-1)/2;
if (arr3[mid] ==x)
return mid;
if(arr3[mid] > x)
return binarySearch(arr3, l, mid -1, x);
return binarySearch(arr3, mid + 1, r, x);
}
return -1;
}
}
My Main class
public class MainTester {
public static void main(String args[]) {
//sorting tester
Sorting obj = new Sorting();
int arr[] = {9,5,4,1,6,10,3,2,7,8};
obj.bubbleSort(arr);
System.out.println("Sorted array:");
obj.printArray(arr);
//binary search tester
int arr3[] = {2,3,5,4,30};
int n = arr3.length;
int x = 10;
int result = binarySearch(arr3, 0, n-1, x);
if (result == -1)
System.out.println("Element not present");
else System.out.println("Element found " + result);
//linear search tester
int arr2[] = {2,3,4,10,30};
int x2 = 10;
int result2 = linearsearch(arr2, x2);
if (result2 == -1)
System.out.print("Element is not present in array.");
else
System.out.print("Element is present " +result2);
}
private static int binarySearch(int[] arr3, int l, int r, int x) {
// TODO Auto-generated method stub
return -1;
}
private static int linearsearch(int[] arr2, int x) {
// TODO Auto-generated method stub
return -1;
}
}
I was expecting this code to test all my methods in the main so I can print the result of my binary and linear search
Here is a working version of your code.
There was still some mistakes. See comments in code below.
Class 'Search'
Class 'MainTester'
Try to avoid repetitive code. If you have some, extract it to another method and call that method.
Hope it helps.