Suppose all oranges are enumerated from 0 to 127, then their weights may be put in an array of length 128:
take the first orange weight, compare it to second, if it is heavier, the heavy orange is found, otherwise enter a loop:
int heavy_index;
if (weights[0] > weights[1])
heavy_index = 0;
else
for (int i = 1; i < 128; ++i) {
if (weights[0] < weights[i])
heavy_index = i;
}
On average it takes "\\approx" 64 comparisons, while the best case scenario only takes 1 and the worst care takes 128 comparisons
Comments
Leave a comment