In: Computer Science
Java Programming
Create a program that prompts the user for an integer number and searches for it within an array of 10 elements. What is the average number of comparisons required to find an element in the array?
Your program should print the number of comparisons required to find the number or determine that the number does not exist.
Try finding the first and last numbers stored in the array.
Run your program several times before computing the average.
import java.util.Scanner;
public class Main
{
public static void main(String[] args) {//linear
search is implemented here
int n,c=0,flag=0;
int a[]={1,2,3,4,5,6,7,8,9,10};//array of 10
elements
Scanner inp=new Scanner(System.in);
System.out.println("Enter a integer
number");
n=inp.nextInt();//read integer from
user
for(int i=0;i<10;i++){
c++;//increment c value for each
Comparison
if(a[i]==n){
flag=1;//set flag to 1 if number n
is found in array
break;
}
}
if(flag==1)
System.out.println("Comparisons:"+c);//print number of
Comparisons
else
System.out.println("Number not
found");
}
}
Screenshots:
The screenshots are attached below for reference.
Please follow them for output.
Average number of comparisons:
The number of comparisons are as shown above in the outputs attached.
For search an element located at index 0, 1 comparison is needed.
For search an element located at index 9, 10 comparison is needed.
For search an element located at index 4, 5 comparison is needed.
For search an element located at index 8, 9 comparison is needed.
The average number of comparisons needed is (1+2+3+4+5+6+7+8+9+10)/10.
The result is floor(5.5) which is 5.