I am working on an assignment for school. Essentially, we are analyzing sorting algorithms and their costs on large sets of numbers. We have a best case (in order already), worst case (reverse order), and average case (random order). However, for almost all of my sorting algorithms, sorting the worst case takes less time than the average case. After reading, it definitely seems like branch prediction is causing this. It is recognizing the pattern (decreasing order) and executing the code quicker than it should be in theory (big O notation).
I've done some research on branch prediction, and while there appears to be ways to optimize it to be faster, I can't find anything on disabling it entirely. Is there a G++ flag I can use? Or a terminal command?
This is an example of my bubble sort algorithm:
void bubble(vector<long> &vector) {
for (int i = 0; i < vector.size() - 1; i++){
for (int j = 0; j < vector.size() - i - 1; j++) {
if (vector[j] > vector[j + 1]) {
long tmp = vector[j];
vector[j] = vector[j+1];
vector[j+1] = tmp;
}
}
}
}
My timings for my average case is almost double for the worst case.