I have a project to sort array[500000] using quickSort algorithm, I've implemented quickSort like this:
public void sort (int[] array){
sort(array, 0, array.length - 1);
}
private void sort (int[] array, int start, int end){
if (start >= end) {
return;
}
var boundary = partition(array, start, end);
sort(array, start, boundary - 1);
sort(array, boundary + 1, end);
}
private int partition(int[] array, int start, int end){
var pivot = array[end];
var boundary = start - 1;
for (int i = start; i <= end; i++)
if (array[i] <= pivot)
swap(array, i, ++boundary);
return boundary;
}
private void swap(int[] array, int index1, int index2){
var temp = array[index1];
array[index1] = array[index2];
array[index2] = temp;
}
So I check it; First, I create array with 500000 elements, using some other class (No need to post), and then I get a copy of the array to be able to use it as unsorted again. When I pass the first array to the first object and calculate the runtime, I get something around 300ms, but when I sort the second array (Copy of first unsorted array), I get something around 150000ms. The question is; why these 2 objects which are made from one class, sort the same array in a very different time? Note that I used both System.currentTimeMillies(); and System.nanoTime();, No difference. Also ran it on both linux and Window, no difference again.
Edited: Main Class:
public static void main(String[] args) {
var arrayBuilder = new ArrayBuilder();
var firstArray = arrayBuilder.getArray();
var secondArray = arrayBuilder.getArray();
var quickSort1 = new QuickSort();
long firstSortStart = System.nanoTime();
quickSort1.sort(firstArray);
long firstSortEnd = System.nanoTime();
long firstSortTotal = firstSortEnd - firstSortStart;
System.out.format("Original QuickSort (Version 1) took %d nano seconds. \n", firstSortTotal);
var quickSort2 = new QuickSort();
long secondSortStart = System.nanoTime();
quickSort2.sort(secondArray);
long secondSortEnd = System.nanoTime();
long secondSortTotal = secondSortEnd - secondSortStart;
System.out.format("Changed QuickSort (Version 2) took %d nano seconds. \n", secondSortTotal);
// this takes ~183861470 nano seconds
quickSorter2.sort(copiedArray);
// this takes ~218316931575 nano secondes