I know that Java can be faster than C++ for some programs, but I definitely did not expect Java to beat C++ at sorting 1000000
elements.
Here is my code for Java:
import java.io.*;
import java.util.*;
public class TestProgram {
public static void main (String[] args) throws IOException{
int[] arr = new int[1000000];
for(int i = 0; i < 1000000; ++i){arr[i] = i;}
for(int i = 0; i < 1000000; ++i){ // shuffles elements
int temp = arr[i], next = Math.random() % 1000000;
arr[i] = arr[next];
arr[next] = temp;
}
double start = System.nanoTime();
Arrays.sort(arr);
System.out.println((System.nanoTime() - start)/1000000); // prints number of milliseconds elapsed
}
}
And this is for C++:
#include <iostream>
#include <fstream>
#include <cmath>
#include <algorithm>
#include <vector>
using namespace std;
int main(){
int arr[1000000];
for(int i = 0; i < 1000000; ++i){arr[i] = i;}
srand(time(nullptr));
for(int i = 0; i < 1000000; ++i){swap(arr[i], arr[rand() % 1000000]);}
double start = clock();
sort(arr, arr + 1000000);
cout << (clock()-start)/(CLOCKS_PER_SEC/1000) << '\n';
return 0;
}
Compiling with -O3 on the C++ program, I get results of around 70 milliseconds. However, the Java program can run in only 27-30 milliseconds, which is quite surprising for me.
Can somebody explain why this happens?