Sponsored
This approach involves sorting the scores in descending order, then iteratively assigning ranks to each score while handling ties appropriately. This can be efficiently achieved using a sorting algorithm followed by a traversal to assign ranks. By maintaining an index while sorting, we can assign ranks directly to the original scores.
Time Complexity: O(n log n) due to the sorting operation.
Space Complexity: O(1), only a fixed amount of additional memory is used for sorting.
1#include <stdio.h>
2#include <stdlib.h>
3
4typedef struct {
5 int id;
6 double score;
7} ScoreEntry;
8
9int compare(const void *a, const void *b) {
10 ScoreEntry *entryA = (ScoreEntry *)a;
11 ScoreEntry *entryB = (ScoreEntry *)b;
12 if (entryA->score < entryB->score) return 1;
13 if (entryA->score > entryB->score) return -1;
14 return 0;
15}
16
17void assignRanks(ScoreEntry entries[], int n) {
18 qsort(entries, n, sizeof(ScoreEntry), compare);
19 int rank = 1;
20 for (int i = 0; i < n; i++) {
21 if (i == 0 || entries[i].score != entries[i - 1].score) {
22 rank = i + 1;
23 }
24 printf("Score: %.2f, Rank: %d\n", entries[i].score, rank);
25 }
26}
27
28int main() {
29 ScoreEntry scores[] = {
30 {1, 3.50}, {2, 3.65}, {3, 4.00}, {4, 3.85}, {5, 4.00}, {6, 3.65}
31 };
32 int n = sizeof(scores) / sizeof(scores[0]);
33 assignRanks(scores, n);
34 return 0;
35}
The C implementation uses a structure to store each score with its ID. The scores are sorted in descending order using `qsort()` and a custom comparator. During sorting, ties are managed by assigning the same rank, replicating an Excel-like RANK function behavior. The solution uses a single scan to determine ranks after sorting.
This approach uses a bucket sort strategy, particularly efficient when scores have a limited range of decimal places. This reduces the complexity substantially in scenarios where HTTP (High Throughput Processing) is required. Counting occurrences of each score allows direct assignment of ranks in descending order of scores efficiently.
Time Complexity: O(n + k), where n is the number of scores, and k is the number of buckets (constant in this case).
Space Complexity: O(k), which is fixed and depends on BUCKET_COUNT.
1
The C bucket sort implementation converts each score based on its proximity to MIN_SCORE using a defined bucket size. Each score increments its corresponding bucket to count occurrences. The ranks are assigned by iteratively checking non-empty buckets from highest to lowest.