为什么处理有序数组比处理无序数组更快?
技术背景
在编写程序时,我们经常会遇到需要对数组进行处理的场景。有时会发现,处理有序数组的速度明显快于处理无序数组。例如,在以下 C++ 和 Java 代码中,对数组进行排序后,主要循环的执行速度提升了数倍。
C++ 示例代码
#include <algorithm>
#include <ctime>
#include <iostream>
int main()
{
// Generate data
const unsigned arraySize = 32768;
int data[arraySize];
for (unsigned c = 0; c < arraySize; ++c)
data[c] = std::rand() % 256;
// !!! With this, the next loop runs faster.
std::sort(data, data + arraySize);
// Test
clock_t start = clock();
long long sum = 0;
for (unsigned i = 0; i < 100000; ++i)
{
for (unsigned c = 0; c < arraySize; ++c)
{
// Primary loop.
if (data[c] >= 128)
sum += data[c];
}
}
double elapsedTime = static_cast<double>(clock()-start) / CLOCKS_PER_SEC;
std::cout << elapsedTime << '\n';
std::cout <