Answer to Question #175421 in Java | JSP | JSF for Lucy

Question #175421

a. An algorithm is a procedure for solving a problem in terms of the actions to execute and the order in which these actions execute. Write an algorithm for the implementation of the sentinel control in Question A Sub Question.

B. For larger datasets, a linear search may be inadequate or perhaps inefficient. What other search method can be employed to return the maximum number from a set of elements in an array. Explain your answer. [5 marks]


1
Expert's answer
2021-03-29T05:48:09-0400

a)



import java.io.*; // import io package, for i/o operations

import java.util.Scanner; // import Scanner class, for taking inputs

class My_Class{ // name of the java file should be My_Class.java

public static void main(String[ ] args)

{

int a,b,c; // declare the integer variables to store three numbers

Scanner sc = new Scanner(System.in); // create an object of Scanner object

  System.out.println("Enter 1 for the product -1 to quit: ");

int tmp;

tmp = sc.nextInt();

while(tmp != -1){

System.out.println("Enter 1 for the product -1 to quit: ");

System.out.println("Enter the three numbers: ");

tmp = sc.nextInt()

a = sc.nextInt(); // take input of 1st number

b = sc.nextInt();   // take input of 2nd number

c = sc.nextInt();    // take input of 3rd number

// to find product of a, b, c

int prod = a*b*c; // declare a variable prod, to store product of a, b, c

   System.out.println("Product of the three numbers is: "+prod); // print the product

}

}

}




b)

Linear search, to search for an element can be inefficient for a very large dataset, as it is an O(n) algorithm. But, we can not search for an element in less than O(n) unless the array given to us is sorted. If the given array is sorted, we can apply the binary search algorithm to search for an element in O(log n), because it gives us a pattern by which we can reduce our search space in half at every step.

To search the maximum element in an array:

case 1: if the array is sorted, we can give the maximum element in O(1), because the maximum is the last element (if sorted in ascending) or the first element (if sorted in descending).

case 2: if the array is unsorted, we will need to search the whole array to find the maximum element, so will require O(n).





Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog