Why processing a sorted array is faster than an unsorted one
Hi everyone. I'm learning C++ and came across a strange performance behavior. I wrote a simple program that sums array elements, but only if they are greater than a certain threshold (e.g., 128). I measured the execution time for sorted and unsorted arrays — and the results shocked me.
Here's the code:
```cpp
#include
#include
#include
#include
int main() {
const int SIZE = 100000;
std::vector data(SIZE);
// Fill with random numbers
for (int i = 0; i < SIZE; ++i) {
data[i] = rand() % 256;
}
// Copy for unsorted case
std::vector unsorted = data;
std::vector sorted = data;
std::sort(sorted.begin(), sorted.end());
No answers yet.
Log in to leave an answer
Blogs