|
| 1 | + |
| 2 | +/*----- Checking the run time of an Array using different approaches -----*/ |
| 3 | + |
| 4 | +import java.util.*; |
| 5 | +import java.util.concurrent.TimeUnit; |
| 6 | + |
| 7 | + |
| 8 | +public class CalculatingRunTime { |
| 9 | + |
| 10 | + public static void main(String args[]){ |
| 11 | + |
| 12 | + int arr[] = new int[(Integer.MAX_VALUE)/10000]; |
| 13 | + |
| 14 | + for(int i=(Integer.MAX_VALUE)/10000; i>0; i--){ |
| 15 | + arr[(Integer.MAX_VALUE)/10000 - i] = i; |
| 16 | + } |
| 17 | + |
| 18 | + /*--- Calculating the run time for sorting using nested for loops: ---*/ |
| 19 | + |
| 20 | + long timeStarts = System.currentTimeMillis(); //Time starts here |
| 21 | + |
| 22 | + for(int i=0; i<arr.length; i++){ |
| 23 | + for(int j=i+1; j<arr.length; j++){ |
| 24 | + if(arr[i]>arr[j]) { |
| 25 | + int bucket = arr[i]; |
| 26 | + arr[i] = arr[j]; |
| 27 | + arr[j] = bucket; |
| 28 | + } |
| 29 | + } |
| 30 | + } |
| 31 | + |
| 32 | + System.out.print("The sorted array in ASC order is:"); |
| 33 | + |
| 34 | + for(int i=0; i<arr.length; i++){ |
| 35 | + System.out.print(" "+arr[i]); |
| 36 | + } |
| 37 | + |
| 38 | + long timeEnds = System.currentTimeMillis(); //Time ends here |
| 39 | + |
| 40 | + long timeInSeconds = TimeUnit.MILLISECONDS.toSeconds(timeEnds - timeStarts); |
| 41 | + |
| 42 | + System.out.printf("%nThe Time taken in seconds is: "+timeInSeconds+" seconds%n"); |
| 43 | + |
| 44 | + |
| 45 | + |
| 46 | + /*--- Checking run time for Array sorting using inbuilt sorting method: ---*/ |
| 47 | + |
| 48 | + |
| 49 | + |
| 50 | + int arr2[] = new int[(Integer.MAX_VALUE)/10000]; |
| 51 | + |
| 52 | + for(int i=(Integer.MAX_VALUE)/10000; i>0; i--){ |
| 53 | + arr2[(Integer.MAX_VALUE)/10000 - i] = i; |
| 54 | + } |
| 55 | + |
| 56 | + long timeStarts2 = System.currentTimeMillis(); //Time starts here |
| 57 | + |
| 58 | + Arrays.sort(arr2); |
| 59 | + |
| 60 | + System.out.print("The sorted array in ASC order is:"); |
| 61 | + |
| 62 | + for(int i=0; i<arr2.length; i++){ |
| 63 | + System.out.print(" "+arr2[i]); |
| 64 | + } |
| 65 | + |
| 66 | + long timeEnds2 = System.currentTimeMillis(); //Time ends here |
| 67 | + |
| 68 | + long timeInSeconds2 = TimeUnit.MILLISECONDS.toSeconds(timeEnds2 - timeStarts2); |
| 69 | + |
| 70 | + System.out.printf("%nThe Time taken in seconds is: "+timeInSeconds2+" seconds%n"); |
| 71 | + |
| 72 | + } |
| 73 | + |
| 74 | + |
| 75 | +} |
| 76 | + |
| 77 | +/* |
| 78 | +* Worst case: |
| 79 | +* |
| 80 | +* The Run time for for-loop came out to be: 21 seconds |
| 81 | +* The Run time for inbuilt sort came out to be: 1 second |
| 82 | +* |
| 83 | +* |
| 84 | +*/ |
| 85 | + |
| 86 | + |
0 commit comments