Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Objective: To gain insight into the performance differences when a series of if-

ID: 3579302 • Letter: O

Question

Objective: To gain insight into the performance differences when a series of if-then-else tests are converted into a switch - case configuration. The specific assignment is to compare the execution times of two routines that perform the same task, but implement the decision processes differently. Assignment: Write a main program which generates a source array which is populated with random numbers in the range of 0 to 999. Write your program so that the size of the array can be changed easily or specified on the command line. Specific requirements are: Use rand() to generate a sequence of random integers. Use the modulus function to limit the original numbers to a range of 0 to 999. Count the number of values which fall in the range of 0 - 199, 200 - 399, 400 - 599, 600 - 799, 800 - 999 using both a switch statement and a sequence of if-then-else statements. Measure how much time it takes to generate a count for all of the numbers with both approaches, and compare the two approaches' execution times. For the case statement, I suggest that you convert the number to an integer form that lends itself to the switch statement. You may use something like: int index = number/200. This will work because the number is an integer and the fractional part of the result is discarded - this is good practice to see the effects of different ways that numbers are represented.

Explanation / Answer

import java.util.Random;
class Main {
public static void main(String[] args) {
Random rand = new Random();
int n = 1000,r,i;
   long startTime,endTime,totalTime;
int[] numbers = new int[n];
int[] bucket = {0,0,0,0,0};
for(i=0;i<n;i++)
numbers[i] = rand.nextInt(999);
startTime = System.currentTimeMillis();
for(i=0;i<n;i++){
int x = numbers[i]/200;
if(x==0)
bucket[0]++;
else if(x==1)
bucket[1]++;
else if(x==2)
bucket[2]++;
else if(x==3)
bucket[3]++;
else if(x==4)
bucket[4]++;
}
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
System.out.println("If else Time:"+totalTime);
  
   startTime = System.currentTimeMillis();
for(i=0;i<n;i++){
int x = numbers[i]/200;
   switch (x){
       case 0:
           bucket[0]++;
       case 1:
           bucket[1]++;
       case 2:
           bucket[2]++;
       case 3:
           bucket[3]++;
       case 4:
           bucket[4]++;
       }
}
endTime = System.currentTimeMillis();
totalTime = endTime - startTime;
System.out.println("switch Time:"+totalTime);
}
}
/* sample output
If else Time: 2
switch Time: 0
*/