I have the following implementation of simple sort algorithms (bubble, select, insert). My goal: measure execution time for these methods on the same random-generated array data with Integer elements. Array size is 10_000.
public void sortBubble() {
for (int i = 0; i < size - 1; i++) {
for (int j = 0; j < size - 1 - i; j++) {
if (data[j].compareTo(data[j + 1]) > 0) {
swap(j, j + 1);
}
}
}
}
public void sortSelect() {
for (int i = 0; i < size - 1; i++) {
int minIndex = i;
for (int j = i + 1; j < size; j++) {
if (data[j].compareTo(data[minIndex]) < 0) {
minIndex = j;
}
}
swap(minIndex, i);
}
}
public void sortInsert() {
for (int i = 1; i < size; i++) {
E temp = data[i];
int in = i;
while (in > 0 && data[in - 1].compareTo(temp) >= 0) {
data[in] = data[in - 1];
in--;
}
data[in] = temp;
}
}
private void swap(int indexA, int indexB) {
E temp = data[indexA];
data[indexA] = data[indexB];
data[indexB] = temp;
}
How I generate data for sorting:
Random random = new Random();
for (int i = 0; i < ARRAY_CAPACITY; i++) {
int value = random.nextInt(MAX_VALUE);
array.add(value);
}
When I use Java 8, my common stable result is the insertion sort is the fastest one. For example:
Sort Bubble took time: 381384 micros.
Sort Select took time: 100343 micros.
Sort Insert took time: 45580 micros.
But when I run the same code on Java 14 and more, suddenly (for me) the selection sort is faster than the insert one:
Sort Bubble took time: 521345 micros.
Sort Select took time: 119718 micros.
Sort Insert took time: 144706 micros.
I've checked a code several times: there are no differences and unusual cases in how I run this code. This issue is reproduced stably. I guess, it's related to changes since the 14th Java version, but I have no idea what exactly. Do you know what can be the main reason for that?
Thanks in advance.