Skip to main content
OverflowAI is here! AI power for your Stack Overflow for Teams knowledge community. Learn more
2 of 7
added 5 characters in body
Yochai Timmer
  • 48.6k
  • 24
  • 150
  • 186

Besides the fact that the branch prediction slows you down, a sorted array has another advantage:
You can have a stop condition instead of just checking the value, this way you loop only over the relevant data, and ignore the rest.

 // sort backwards (higher values first)
 std::sort(data, data + arraySize, std::greater<int>());

 for (unsigned c = 0; c < arraySize; ++c)
 {
       if (data[c] < 128)
              break;
       sum += data[c];               
 }
Yochai Timmer
  • 48.6k
  • 24
  • 150
  • 186