#include "stdafx.h" #include using namespace std; struct Student { char name[80]; double GPA; int ID; }; // used in call to qsort int compStudentsGPA(const void *ap, const void *bp) { double gpa1, gpa2; gpa1 = ((Student *)ap)->GPA; gpa2 = (*((Student *)bp)).GPA; // same as above if (gpa1 < gpa2) return -1; else return 1; } // used in call to qsort int compStudentsID(const void *ap, const void *bp) { int id1, id2; id1 = ((Student *)ap)->ID; id2 = ((Student *)bp)->ID; if (id1 < id2) return -1; else if (id1 == id2) return 0; else return 1; } // used in call to qsort int compInt(const void *ap, const void *bp) { int *aip = (int *)ap; int *bip = (int *)bp; if (*aip < *bip) return -1; else if (*aip == *bip) return 0; else return 1; // return *((int *)a) - *((int *)b); } int main() { int A[10] = { 45, 23, 67, 8, 12, 69, 30, 22, 98, 546 }; qsort(A, 10, sizeof(int), compInt); cout << "A sorted!" << endl; Student student[100]; // initialize students to random values for (int i = 0; i < 100; i++) { student[i].name[0] = rand() % 26 + 'A'; student[i].name[1] = rand() % 26 + 'a'; student[i].name[2] = rand() % 26 + 'a'; student[i].name[3] = 0; student[i].GPA = (double)rand() / RAND_MAX * 4.0; student[i].ID = rand(); } // sort the data based on GPA qsort(student, 100, sizeof(Student), compStudentsGPA); // sort the data based on ID qsort(student, 100, sizeof(Student), compStudentsID); return 0; }