To radically change the subject, assuming that labels can only be in the range 0..100, consider creating an array that contains the grade number for the grade:
enum { MAX_SCORE = 100 }; static const int upper_bound[] = { 60, 69, 72, 75, 80, 82, 85, 89, 92, MAX_SCORE+1 }; enum { N_BOUNDS = sizeof(upper_bound) / sizeof(upper_bound[0]) }; int grade_for_score[MAX_SCORE + 1]; int score = 0; for (int i = 0; i < N_BOUNDS; i++) { while (score < upper_bound[i]) grade_for_score[score++] = i; }
The compensation for the tuning work is that the evaluation processing is trivial:
assert(data[y] >= 0 && data[y] <= MAX_SCORE); grades[grade_for_score[data[y]]++;
This can be useful because no conditional expressions are required to process the estimates as they become available, in addition to the basic check that the estimate is in the range [0..MAX_SCORE]. Of course, it uses some data space. Of course, if the data is read from a file (or database), the I / O interaction time completely increases the sorting time, and optimization is almost pointless.
Work code:
#include <assert.h> #include <stdio.h> int main(void) { /* Setup */ enum { MAX_SCORE = 100 }; static const int upper_bound[] = { 60, 69, 72, 75, 80, 82, 85, 89, 92, MAX_SCORE+1 }; enum { N_BOUNDS = sizeof(upper_bound) / sizeof(upper_bound[0]) }; int grade_for_score[MAX_SCORE + 1]; int score = 0; for (int i = 0; i < N_BOUNDS; i++) { while (score < upper_bound[i]) grade_for_score[score++] = i; } /* Scoring - test each score from [0..MAX_SCORE] */ int grades[N_BOUNDS] = { 0, }; int data[1]; int y = 0; for (int i = 0; i <= MAX_SCORE; i++) { data[y] = i; assert(data[y] >= 0 && data[y] <= MAX_SCORE); grades[grade_for_score[data[y]]]++; } /* Print grades */ int sum = 0; for (int i = 0; i < N_BOUNDS; i++) { sum += grades[i]; printf("Grade %d: %3d (cumulative %3d)\n", i, grades[i], sum); } return 0; }
Note that at compile time, you could initialize the grade_for_score table rather than run it at runtime:
int grade_for_score[] = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 5, 5, 6, 6, 6, 7, 7, 7, 7, 8, 8, 8, 9, 9, 9, 9, 9, 9, 9, 9, 9 };
However, the table is easily computed from the upper bounds table, and computers are better suited to counting rights than people, so it’s better to create a table at run time.
Execution Example:
Grade 0: 60 (cumulative 60) Grade 1: 9 (cumulative 69) Grade 2: 3 (cumulative 72) Grade 3: 3 (cumulative 75) Grade 4: 5 (cumulative 80) Grade 5: 2 (cumulative 82) Grade 6: 3 (cumulative 85) Grade 7: 4 (cumulative 89) Grade 8: 3 (cumulative 92) Grade 9: 9 (cumulative 101)