The instructions to answer my question are below in bulletpo
The instructions to answer my question are below in bulletpoints, and write the code in Java with comments.
A classic O(N) algorithm is linear search, where every item is looked at until the target is found Write a for loop to search the array of integers the_array to find the match for the value in the variable targetval Use the variable cnt to control the loop AND when the loop terminates it MUST contain the number of comparisons to find the value That number must be +1 of the slot the item was found in, if the item was found in slot zero, it took one comparison to find it Do not declare or initialize the_array or targetval it will be done for you. Write only the loop and remember if the value was found in slot 3 it took 3+1 or 4 comparisons to find itSolution
Code:
class LinearSearch
{
public static void main(String args[])
{
int cnt, slot;
for (cnt = 0; cnt < the_array.length; cnt++) /* loop to traverse each element in an array to find whether search element exist or not*/
{
if (the_array[cnt] == targetval) /* here we are comparing each array element with the search element*/
{
slot=cnt; /* For calculating the comparsions we are assigning the search found location value to slot variable*/
break; /* once search element is found we are breaking the loop*/
}
}
/* checking whether cnt is equal to the array length, if it is equal that means search element is not found in the array*/
if(cnt == the_array.length){
System.out.println(\"Search element was not found\");
}
else{
System.out.println(\"Search value was found in slot\" + cnt +\" and it took\" + cnt+1+ \"comparsion to found the element\"); /*if element is found then we are dispalying the location and calculating number of comparsions*/
}
}
}
