I wrote two simplest sorting algorithms that are almost the same, but the one that has more than half operations to perform takes double the time. It is beyond my understanding why that is happening.
Any pointers would be much appreciated since I'm trying to understand the most efficient way to sort, considering different circumstances, a sort as simple as that got me puzzled.
public class Sort{
static long timerStart;
static long timerEnd;
static long passedTime;
public static void main(String[] args) {
double[] arr = createDoubleArray(10000);
double[] arr2 = Arrays.copyOf(arr,arr.length);
startTimer();
sortDoubleArrayFast(arr);
stopTimer();
computationTime();
startTimer();
sortDoubleArraySlow(arr2);
stopTimer();
computationTime();
}
public static void startTimer(){
timerStart = System.currentTimeMillis();
}
public static void stopTimer(){
timerEnd = System.currentTimeMillis();
}
public static void computationTime(){
passedTime = timerEnd-timerStart;
System.out.println("The operations took: " +passedTime+"ms");
}
public static double[] createDoubleArray(int size){
double[] output = new double[size];
for (int i = 0; i < size; i++) {
output[i] = Math.random()*10000000;
}
return output;
}
public static double[] sortDoubleArraySlow(double[] input){
double tmp;
int operationNumber = 0;
for (int j = 0; j < input.length; j++) {
for (int i = 0; i < input.length; i++) {
operationNumber++;
if(input[i]>input[j]){
tmp = input[j];
input[j] = input[i];
input[i] = tmp;
}
}
}
System.out.println("Operation number in Slow: "+operationNumber);
return input;
}
public static double[] sortDoubleArrayFast(double[] input){
double tmp;
int operationNumber = 0;
for (int j = 0; j < input.length-1; j++) {
for (int i = j+1; i < input.length; i++) {
operationNumber++;
if(input[i]>input[j]){
tmp = input[j];
input[j] = input[i];
input[i] = tmp;
}
}
}
System.out.println("Operation number in Fast: "+operationNumber);
return input;
}
}