I found Java's Arrays.sort() method is much slower than my simple sorting method (based on counting sort).
I wrote a program to compare running time my simple sorting technique with Java's Arrays.sort() method. I noticed my implementation runs much faster (it needs 1/3 time compared with system method).
Below is my implementation.
I keep track of all the elements in a secondary array and I copied back all the elements to the main array before return.
static void mySort(int[] num2, int n)
{
double startTime, endTime;
startTime = System.currentTimeMillis();
int[] sortedData = new int[n];
for (int i = 0; i < n; i++)
sortedData[num2[i]]++;
int index = 0;
for (int i = 0; i < n; i++)
if (sortedData[i] > 0)
{
for (int j = 0; j < sortedData[i]; j++)
{
num2[index++] = i;
}
}
endTime = System.currentTimeMillis();
System.out.println("Time taken for my sort: "
+ (endTime - startTime) + " ms");
}
static void systemSort(int[] num)
{
double startTime, endTime;
startTime = System.currentTimeMillis();
Arrays.sort(num);
endTime = System.currentTimeMillis();
System.out.println("Time taken for System sort: " +
(endTime - startTime) + " ms");
}
public static void main(String[] args)
{
int size = 50000000;
int[] origArray = new int[size];
int[] origArray2 = new int[size];
Random rn = new Random();
System.out.println("Taking " + size + " inputs randomly...");
for (int i = 0; i < size; i++)
{
origArray[i] = rn.nextInt(size);
origArray2[i] = origArray[i];
}
System.out.println("Done!");
System.out.println("\n\nFrom System sort: ");
systemSort(origArray);
System.out.println("\n\nFrom my sort: ");
mySort(origArray2, size);
}
Here is the output:
Taking 5000000 inputs randomly...
Time taken for System sort: 652.0 ms
Time taken for my sort: 160.0 ms
Taking 50000000 inputs randomly...
Time taken for System sort: 5737.0 ms
Time taken for my sort: 2176.0 ms
If we can buy a good amount of execution time with the cost of memory (considering memory is less expensive now a days) then why not we taking advantages of it?
Any thoughts? Thank you.