I want to addtiming execution in java code but I don't know how? Here is the code of Bucket sort

import java.util.*;


    public class BucketSort{

       public static void sort(int[] a, int maxVal) {
          int [] bucket=new int[maxVal+1];

          for (int i=0; i<bucket.length; i++) {
             bucket[i]=0;
          }

          for (int i=0; i<a.length; i++) {
             bucket[a[i]]++;
          }

          int outPos=0;
          for (int i=0; i<bucket.length; i++) {
             for (int j=0; j<bucket[i]; j++) {
                a[outPos++]=i;
             }
          }
       }


       public static void main(String[] args) {
          int maxVal=100000;
          int [] data= {1000, 10000, 15000, 25000, 30000, 45000, 50000, 60000, 75000, 90000, 100000}; 

          System.out.println("Array: " + Arrays.toString(data));
          sort(data,maxVal);
          System.out.println("Sorted array Bucket Sort:  " + Arrays.toString(data));
       }
    }

Recommended Answers

All 3 Replies

The System class has methods to get the current time. There's a nanosecond version as well, but your pc may not be able to supply such precise time.
Just get the time before and after the sort, subtract them for elapsed time. If the result is less than about a second it won't be very accurate timing, so repeat the sort a few times in a loop until it takes a decent measurable time.

You can see on this link 3 different type of sorting (Bubble sort, Insertion sort and Selection sort) with time need to sort.
You can find there code how to messure speed, it's just a few lines of code.
But as JamesCherrill said it is not so accurate but you will have a average how much time your code need to sort things out.

If you have any questions feel free to ask. Mike.

Thanks a lot James and Mike, I will try this :D Thanks again

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.