Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Write a program with at least 3 functions. One function can do a linear search o

ID: 3704465 • Letter: W

Question

Write a program with at least 3 functions. One function can do a linear search on an array. The other can do a binary search. You will need to modify the binary search code to keep track of how many numbers it checked before it found the number. Use function header/prototypes. In main, make an array of 30 sorted numbers. (Initialize the array with the numbers.) Do searches on the arrays on the same numbers. Print out how many elements it needs to check before it finds the number with each type of search. Do at least 6 linear searches and 6 binary searches.

Explanation / Answer

import java.util.Scanner;

public class Search {

public static void main(String[] args) {
Scanner sc=new Scanner(System.in);
int [] inputArray= {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,
17,18,19,20,21,22,23,24,25,26,27,28,29,30};
int sizeofarray=inputArray.length;
System.out.println("Given array:");
for(int l=0;l<sizeofarray;l++){
System.out.print(inputArray[l]+" ");
}
System.out.println("");
System.out.println("1 : Run the Program");
System.out.println("2 : Exit");
for(;;){
System.out.println("Please Enter the Option:");
int option = sc.nextInt();
if(option==1){
System.out.println("Please Enter Search Number:");
int searchNumber=sc.nextInt();
linearSearch(inputArray ,sizeofarray ,searchNumber);
binarySearch(inputArray, 0, sizeofarray-1, searchNumber);
continue;
}
else{
break;
}
}
}

public static void linearSearch(int arr[], int size, int key){
for(int i=0; i<size; i++){
if(arr[i]==key){
int y=i+1;
System.out.println("Your number was Found at "+y+"th iteration ");
}
}
}
public static void binarySearch(int arr[], int first, int last, int key){
int mid = (first + last)/2;
int iteration =0;
while( first <= last ){
if ( arr[mid] < key ){
first = mid + 1;
}else if ( arr[mid] == key ){
// System.out.println("Element is found at index: " + mid);
break;
}else{
last = mid - 1;
}
mid = (first + last)/2;
iteration++;
}
if(iteration>=0){
iteration=iteration+1;
System.out.println("Your number was Found at "+iteration+"th iteration ");
}
if ( first > last ){
System.out.println("Element is not found!");
}
}
}

Please find above code and run in any java ide.... If any queries or issuesifound, revert back..

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote