Created
August 12, 2019 07:14
-
-
Save tjkhara/98c18771b9cd522626c62c6084312eaa to your computer and use it in GitHub Desktop.
sorting an array of structs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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