(i) Write a java program that reads three (3) int variables and performs the below operations: i. Prints out their product ii. Prints out the maximum of the numbers Do not use any inbuilt Java Methods to return the maximum. Extra marks will be awarded for clarity of code and comments. [8 marks]
(ii) Algorithms perform differently on different data sets and as such we may be interested in either their Best-case, Worst-case or Average-case scenarios. Explain why the Worst-case for an insertion sort is with reverse-sorted data. [6 marks]
(i)
Ans:
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 the first number: ");
a = sc.nextInt(); // take input of 1st number
System.out.println("Enter the second number: ");
b = sc.nextInt(); // take input of 2nd number
System.out.println("Enter the third 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
// to find maximum among three numbers
int max = a; // declare a variable max to store the maximum number, initialised with max = a.
// assuming a is the maximum, we will compare with other numbers too
if(b>max) max = b; // if b is greater than max, update max
if(c>max) max = c; // if c is greater than max, update max
System.out.println("The maximum number among these numbers is: "+max); //print the maximum number
}
}
(ii)
Ans: Algorithms do perform differently on different data sets. The worst-case time complexity of an algorithm will be on a different data set, and the average case or best case time complexities will be on the different data set. Let us consider the example of the Insertion sort algorithm:
There are 2 lops in the insertion sort algorithm. One that iterates from the second element to the last element of the array. Hence, this loop will always run (n-1) times, where n is the number of elements in the array, no matter what the array is. But, the inner loop runs from the current position of the outer loop to the first element of the array. What is happening is, we are comparing the ith element with (i-1)th element, if arr[i-1] > arr[i], we shall swap them. Now, the catch is, if the array is sorted in reverse order this cons=dition will always be true. So, the second or inner loops will always run. That is why the worst-case complexity will be in this case, which is O(n^2).
Example: arr[] = {9,8,7,6,5,4,3,2,1,0}
- first loop will run 9 times (n-1)
- second loop will run 1+2+3+4+5+6+7+8+9 = 45 times.
so, in total 9 + 45 = 54 times.
Comments
Leave a comment