Warum ist die Verarbeitung eines sortierten Arrays schneller als die Verarbeitung eines unsortierten Arrays?Java

Java-Forum
Anonymous
 Warum ist die Verarbeitung eines sortierten Arrays schneller als die Verarbeitung eines unsortierten Arrays?

Post by Anonymous »

In diesem C++-Code macht das Sortieren der Daten (vor der zeitgesteuerten Region) die Primärschleife ~6x schneller:

Code: Select all

#include 
#include 
#include 

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(clock()-start) / CLOCKS_PER_SEC;

std::cout

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post