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

Look at the two different codes below. Analyze their bigO performance difference

ID: 3604941 • Letter: L

Question

Look at the two different codes below. Analyze their bigO performance difference and determine which one should be the better design.

public class ClockA{ public static void main(String[]args)throws InterruptedException{

int sec=0,min=0,hr=0; for(;;sec++){ if(sec==60){min++;sec=0;}

if(min==60){hr++;min=0;} if(hr==24){hr=0;}

System.out.printf("The time is:%02d:%02d:%d ",hr,min,sec);

Thread.sleep(1000); } } }

public class ClockB{

public static void main(String[]args)throws InterruptedException{

for(int hr=0;hr<24;hr++)

{ for(int min=0;min<60;min++)

{ for(int sec=0;sec<60;sec++){

System.out.printf("The time is:%02d:%02d:%d ",hr,min,sec);

Thread.sleep(1000); } } } } }

Explanation / Answer

int sec = 0, min = 0, hr = 0;

               for (;; sec++) {

                   if (sec == 60) {

                       min++;

                       sec = 0;

                   }

                   if (min == 60) {

                       hr++;

                       min = 0;

                   }

                   if (hr == 24) {

                       hr = 0;

                   }

                   System.out.printf("The time is:%02d:%02d:%d ", hr, min, sec);

                   Thread.sleep(1000);

               }



This above has time complexity of O(60*60*24) . Explanation is , we have one loop one runs for 60, 60 and 24 times. So overall time complexity is 60*60*24

for ( int hr = 0; hr < 24; hr++) {

               for ( int min = 0; min < 60; min++) {

                   for (int sec = 0; sec < 60; sec++) {

                       System.out.printf("The time is:%02d:%02d:%d ", hr, min, sec);

                       Thread.sleep(1000);

                   }

               }


This above has time complexity of O(60*60*24) . Explanation is , we have three loop one runs for 60, 60 and 24 times. SO overall time complexity is 60*60*24


(1) is poorly design because there are lot of comparison at each places. That will also take some time. Its constant time although but its poorly designed.

(2) with three for loop is designed well because there are less comparisons at each step where as in (2) will compare with multiple if and then print the result.

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at drjack9650@gmail.com
Chat Now And Get Quote