I have read in many places that the best case for those algorithms is when the array is already sorted and so making the program run them faster. For some reason, When I test the algorithms with unsorted and the same but sorted values, they run faster in the first case. Why?
This is the code for bubble sort:
// ----------------- (1) Bubble Sort -----------------------------
// Unsorted
long startTime11 = System.nanoTime();
Sorting.bubbleSort(wordsToSort);
long endTime11 = System.nanoTime();
long timeLapsed11 = endTime11 - startTime11;
// Already sorted
long startTime12 = System.nanoTime();
Sorting.bubbleSort(wordsToSort);
long endTime12 = System.nanoTime();
long timeLapsed12 = endTime12 - startTime12;
// formats time with commas
String formated11 = formatter.format(timeLapsed11);
String formated12 = formatter.format(timeLapsed12);
bubbleSort method:
private static void bubbleSort(String[] arr, int n) {
for (int i = 0; i < n - 1; ++i)
{
for (int j = 0; j < n - i - 1; ++j)
{
if (arr[j + 1].compareTo(arr[j]) < 0)
{
String temp = arr[j + 1];
arr[j + 1] = arr[j];
arr[j] = temp;
}
}
}
}
CPU Time:
Unsorted: 11, 372, 240, 025, 900 nanoseconds.
Sorted: 22, 020, 911, 806, 900 nanoseconds.
The array has more than 600,000 elements in it.
More case results:
Test two of the array of +600000 elements:
Unsorted: 11, 392, 317, 750, 900 nanoseconds.
Sorted: 22, 024, 687, 559, 200 nanoseconds.
Array of 15000 words:
Unsorted: 1, 407, 057, 900 nanoseconds.
Sorted: 1, 650, 519, 600 nanoseconds.
Unsorted: 1, 430, 736, 200 nanoseconds.
Sorted: 1, 645, 250, 000 nanoseconds.
Array of 15000 words (Warmup phase added; advised from the comments)
Unsorted: 1, 453, 011, 900 nanoseconds.
Sorted: 1, 660, 550, 800 nanoseconds.
Unsorted: 2, 025, 017, 800 nanoseconds.
Sorted: 2, 466, 999, 700 nanoseconds.
Array of 2500 words
Unsorted: 44, 016, 900 nanoseconds.
Sorted: 20, 703, 300 nanoseconds.
Unsorted: 47, 074, 400 nanoseconds.
Sorted: 36, 121, 700 nanoseconds.
Array of 600 words
Unsorted: 7, 104, 600 nanoseconds.
Sorted: 1, 392, 100 nanoseconds.
Unsorted: 7, 144, 500 nanoseconds.
Sorted: 1, 324, 600 nanoseconds.
Here is the code with some txt files to test them and know better how to answer: https://github.com/Obed-Padilla/Sorting-algorithms