Sort Records

Lab C Intermediate 20 points

Read n students name mark, sort them by mark descending (ties by name) with an insertion sort on the struct array, and print them ranked.

Input

n, then n lines.

Output

n lines rank. name mark

Example

Input

4
zed 70
amy 90
bob 70
cy 85

Output

1. amy 90
2. cy 85
3. bob 70
4. zed 70
Sample input available Sample output available
Editor
C

Hints

Structs can be assigned with = (the whole struct is copied).

A helper decides which record comes first.

Solution explanation

Struct assignment copies every field, which makes sorting records straightforward.

Show solution
#include <stdio.h>
#include <string.h>

typedef struct {
    char name[30];
    int mark;
} Student;

int before(Student *a, Student *b) {
    if (a->mark != b->mark) return a->mark > b->mark;
    return strcmp(a->name, b->name) < 0;
}

int main() {
    int n;
    Student s[50];
    scanf("%d", &n);
    for (int i = 0; i < n; i++) scanf("%s %d", s[i].name, &s[i].mark);
    for (int i = 1; i < n; i++) {
        Student key = s[i];
        int j = i - 1;
        while (j >= 0 && before(&key, &s[j])) {
            s[j + 1] = s[j];
            j--;
        }
        s[j + 1] = key;
    }
    for (int i = 0; i < n; i++) printf("%d. %s %d\n", i + 1, s[i].name, s[i].mark);
    return 0;
}
Output
Answer
HOME LEARN COMMUNITY DASHBOARD