Skip to content

Instantly share code, notes, and snippets.

@maxgoren
Last active October 19, 2021 20:03
Show Gist options
  • Save maxgoren/878b7f5cd28ce416fa736b8090f0ab70 to your computer and use it in GitHub Desktop.
Save maxgoren/878b7f5cd28ce416fa736b8090f0ab70 to your computer and use it in GitHub Desktop.
#include <iostream>
using namespace std;
struct Student {
std::string name;
int age;
int grade_level;
double gpa;
};
bool nameCmp(Student *lhs, Student *rhs)
{
return lhs->name < rhs->name;
}
bool ageCmp(Student *lhs, Student *rhs)
{
return lhs->age < rhs->age;
}
bool grade_levelCmp(Student *lhs, Student *rhs)
{
return lhs->grade_level < rhs->grade_level;
}
bool gpaCmp(Student *lhs, Student *rhs)
{
return lhs->gpa < rhs->gpa;
}
template <typename T>
void swap(T arr, int a, int b)
{
auto tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
}
template <typename T>
void selectionSort(T arr[], int n, bool (*cmp)(T,T))
{
for (int i = 0; i < n; i++)
{
int l = i;
for (int j = i; j < n; j++)
{
if (cmp(arr[j], arr[l]))
{
l = j;
}
}
swap(arr, i, l);
}
}
void printStudentArray(Student* arr[], int n)
{
for (int i = 0; i < n; i++)
{
cout<<" Name: "<<arr[i]->name<<"\n";
cout<<" Age: "<<arr[i]->age<<"\n";
cout<<"Grade: "<<arr[i]->grade_level<<"\n";
cout<<" GPA: "<<arr[i]->gpa<<"\n";
cout<<"-----------------\n";
}
}
int main()
{
int num_students = 5;
Student *students[num_students];
students[0] = new Student{"Max", 34, 16, 3.5};
students[1] = new Student{"Jessica", 22, 16, 3.75};
students[2] = new Student{"Adam", 21, 15, 2.75};
students[3] = new Student{"Stefani", 19, 14, 4.0};
students[4] = new Student{"Lola", 20, 15, 3.4};
cout<<"Sorted By Name:\n-------------------\n";
selectionSort(students, num_students, nameCmp);
printStudentArray(students, num_students);
cout<<"Sorted by GPA\n----------------\n";
selectionSort(students, num_students, gpaCmp);
printStudentArray(students, num_students);
cout<<"Sorted by Grade level:\n----------------------\n";
selectionSort(students, num_students, grade_levelCmp);
printStudentArray(students, num_students);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment