-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path3_1_qsort_student.cpp
71 lines (54 loc) · 1.63 KB
/
3_1_qsort_student.cpp
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
#include <iostream>
#define D_ARRAY_SIZE 10
/*
Using QSORT to sort student structs based on grades and Student ID
*/
using namespace std;
struct student {
int grade;
int studentId;
char name[10];
};
int studentIdCompareFunc(const void * student1, const void * student2);
int studentGradeCompareFunc(const void * voidA, const void * voidB);
int main()
{
student studentArray[D_ARRAY_SIZE] = {
{81, 10009, "Aretha"},
{70, 10008, "Candy"},
{68, 10010, "Veronica"},
{78, 10004, "Sasha"},
{75, 10007, "Leslie"},
{100, 10003, "Alistair"},
{98, 10006, "Belinda"},
{84, 10005, "Erin"},
{28, 10002, "Tom"},
{87, 10001, "Fred"},
};
int sizeOfStudentStruct = sizeof(student);
qsort(studentArray, D_ARRAY_SIZE, sizeOfStudentStruct, studentIdCompareFunc);
for (int i = 0; i < D_ARRAY_SIZE; i++)
{
printf ("%d (%s) ", studentArray[i].studentId, studentArray[i].name);
}
cout << "\nThe top grades are:\n";
qsort(studentArray, D_ARRAY_SIZE, sizeOfStudentStruct, studentGradeCompareFunc);
for (int i = 0; i < D_ARRAY_SIZE; i++)
{
printf ("%s: %d \n", studentArray[i].name, studentArray[i].grade);
}
cin.get();
return 0;
}
int studentIdCompareFunc(const void * voidA, const void * voidB)
{
student* st1 = (student *) voidA;
student* st2 = (student *) voidB;
return st1->studentId - st2->studentId;
}
int studentGradeCompareFunc(const void * voidA, const void * voidB)
{
student* st1 = (student *) voidA;
student* st2 = (student *) voidB;
return st2->grade - st1->grade;
}