-
Notifications
You must be signed in to change notification settings - Fork 0
/
scoreSort.c
100 lines (87 loc) · 1.94 KB
/
scoreSort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
#include <stdio.h>
#include <string.h>
typedef struct Record
{
char name[20];
int score;
} record_t;
typedef unsigned int uint;
void swap_record(record_t *a, record_t *b);
int is_present(record_t records[], const char *name);
uint read_record_entry(record_t records[], int index);
void sort_record(record_t records[], uint size);
void print_record_entry(record_t record);
int main(void)
{
uint n_ent = 0, n_rec = 0;
scanf("%d", &n_ent);
record_t records[20];
memset(&records, 0, sizeof(records));
for (uint i = 0; i < n_ent; i++)
{
n_rec += read_record_entry(records, n_rec);
}
sort_record(records, n_rec);
for (uint i = 0; i < n_rec; i++)
{
print_record_entry(records[i]);
}
return 0;
}
void swap_record(record_t *a, record_t *b)
{
record_t temp;
temp = *a;
*a = *b;
*b = temp;
}
int is_present(record_t records[], const char *name)
{
for (int i = 0; records[i].name[0] != '\0'; i++)
{
if (strcmp(records[i].name, name) == 0)
{
return i;
}
}
return -1;
}
uint read_record_entry(record_t records[], int index)
{
char name[20];
int score, ent_i;
scanf("%s%d", name, &score);
ent_i = is_present(records, name);
if (ent_i < 0)
{
strcpy(records[index].name, name);
records[index].score = score;
return 1;
}
else
{
records[ent_i].score += score;
return 0;
}
}
void sort_record(record_t records[], uint size)
{
// Use bubble sort to achieve stable sort.
int next_it = 1;
while (next_it)
{
next_it = 0;
for (int i = 0; i < size - 1; i++)
{
if (records[i].score < records[i + 1].score)
{
swap_record(&records[i], &records[i + 1]);
next_it = 1;
}
}
}
}
void print_record_entry(record_t record)
{
printf("%s %d\n", record.name, record.score);
}