Skip to content

Instantly share code, notes, and snippets.

@tjkhara
Created August 12, 2019 07:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tjkhara/98c18771b9cd522626c62c6084312eaa to your computer and use it in GitHub Desktop.
Save tjkhara/98c18771b9cd522626c62c6084312eaa to your computer and use it in GitHub Desktop.
sorting an array of structs
#include <iostream>
#include <string>
using namespace std;
struct employee
{
string name;
int age;
};
// Prototypes
void showArray(const employee array[], int size);
void sortArray(employee array[], int size);
int main()
{
struct employee empArray[3];
// Getting the data
for (size_t i = 0; i < 3; i++)
{
cout << "Employee " << i + 1 << endl;
cout << "Enter name " << endl;
cin >> empArray[i].name;
cout << "Enter age " << endl;
cin >> empArray[i].age;
}
cout << "\n\n\n"
<< endl;
sortArray(empArray, 3);
showArray(empArray, 3);
return 0;
}
// show array
void showArray(const employee array[], int size)
{
for (int count = 0; count < size; count++)
{
cout << array[count].name << " " << array[count].age << " ";
cout << endl;
}
}
// sort array
void sortArray(employee array[], int size)
{
bool swapped;
do
{
swapped = false;
for (size_t i = 0; i < (size - 1); i++)
{
if (array[i].age > array[i + 1].age)
{
swap(array[i], array[i + 1]);
swapped = true;
}
}
} while (swapped);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment