Java Program to calculate the time of sorting an array



To calculate the time of sorting an array, let us first create an array and add elements to it −

int[] arr = new int[1000];
for (int i = 0; i < arr.length; i++) {
   arr[i] = (int)(i + 20);
}

Now, set tow Date variables i.e. for past and future to get the time of sorting. Between both the dates, use sort() to sort the array −

Date past = new Date();
Arrays.sort(arr);
Date future = new Date();

Get the difference to calculate the time of sorting −

(future.getTime() - past.getTime()

Example

 Live Demo

import java.util.Arrays;
import java.util.Date;
public class Demo {
   public static void main(String[] args) {
      int[] arr = new int[1000];
      for (int i = 0; i < arr.length; i++) {
         arr[i] = (int) (i + 20);
      }
      Date past = new Date();
      Arrays.sort(arr);
      Date future = new Date();
      System.out.println("Time (milliseconds) = " + (future.getTime() - past.getTime()));
   }
}

Output

Time (milliseconds) = 2
Samual Sam
Samual Sam

Learning faster. Every day.


Advertisements