In: Computer Science
(JAVA)
Create a program that takes in 15 numbers in sorted order from the console and stores them in a 1D array of size 15.
Next, prompt the user for a number to search for in the array (target).
Then, print the array.
Next, search the array using a linear search – printing out each of the indices (or “indexes”) that are being examined until the algorithm either finds the target or doesn’t.
Then, do the same thing for a binary search.
The program should behave like the samples below:
Sample 1
slot 0: 0
slot 1: 1
slot 2: 2
slot 3: 3
slot 4: 4
slot 5: 5
slot 6: 6
slot 7: 7
slot 8: 8
slot 9: 9
slot 10: 10
slot 11: 11
slot 12: 12
slot 13: 13
slot 14: 14
Enter a target: 15
0|1|2|3|4|5|6|7|8|9|10|11|12|13|14|
0 1 2 3 4 5 6 7 8 9 10 11 12 13 14
7 11 13 14
Sample 2
slot 0: 3
slot 1: 11
slot 2: 45
slot 3: 57
slot 4: 81
slot 5: 125
slot 6: 129
slot 7: 311
slot 8: 333
slot 9: 361
slot 10: 402
slot 11: 412
slot 12: 475
slot 13: 499
slot 14: 501
Enter a target: 402
3|11|45|57|81|125|129|311|333|361|402|412|475|499|501|
0 1 2 3 4 5 6 7 8 9 10
7 11 9 10
import java.util.*;
public class Main{
public static void linear_search(int[] a,int t){
for(int i=0;i<15;i++){//traverse the array
if(t==a[i]){
System.out.print(i+" ");//check if element is equal to target
break;
}
else
System.out.print(i+" ");
}
}
public static void binary_search(int[] a,int t){
int l=0,h=14;
while(l<=h){//loop till l is less than or equal to h
int m=l+(h-l)/2;
if(a[m]==t)//compare element and break loop if equal
{
System.out.print(m+" ");
break;
}
if(a[m]<t){//update l if element is less than target
System.out.print(m+" ");
l=m+1;
}
else{
System.out.print(m+ " ");
h=m-1;//update h if element is greater than target
}
}
}
public static void main(String []args){
Scanner inp=new Scanner(System.in);
int a[]=new int[15];
for(int i=0;i<15;i++){
System.out.print("slot "+i+":");
a[i]=inp.nextInt();//read array elements from user
}
System.out.print("Enter a target");
int t=inp.nextInt();
for(int i=0;i<15;i++){
System.out.print(a[i]+"|");//print array
}
System.out.println();
linear_search(a,t);//call functions
System.out.println();
binary_search(a,t);
}
}
Screenshots:
The screenshots are attached below for reference.
Please follow them for output.
Please upvote my answer. Thank you.