#include <iostream>
#include <string>
usingnamespace std;
constint Amoutfamily = 4; // How big the family is.
// ClASS:
class Person{
public:
string name;
int age;
void Print(){
cout << "Name: " << name << " and Age: " << age << endl;
}
};
// Function: LinearSearch: Search for a person in a list
int LinearSearch(Person family[], int Amoutfamily, int a){
int n = Amoutfamily;
for(int i = 0; i < n; i++){ // Går igenom hela listan.
// Is it the number we are searching for?
if(family[i].age == a)
return i;
}
return -1; // Person were not found
}
void swap(Person &p, Person &q){ // Need this in the code
Person temp;
temp.name = p.name;
temp.age = p.age;
p.name = q.name;
p.age = q.age;
q.name = temp.name;
q.age = temp.age;
}
// BubbleSort, sorting Person by age
void bubblesort(Person family[], int Amoutfamily){
// The outer loop, going through all list
for(int i = 0; i < Amoutfamily; i++){
//Inner loop, going through element by element
int nrleft = Amoutfamily - i; // To se how many has been gone through
for(int j = 0; j < nrleft; j++){
if(family[j].age > family[j+1].age){ // Compare the elements
swap(family[j], family[j+1]);
}
}
}
// Write the list:
for(int i = 0; i < Amoutfamily; i++){
family[i].Print();
}
}
// FUNCTION: Main, start the program
int main(){
Person family[Amoutfamily];
// Create a list and fill with persons
family[0].name = "Mats";
family[0].age = 52;
family[1].name = "Carina";
family[1].age = 48;
family[2].name = "Alex";
family[2].age = 20;
family[3].name = "Emily";
family[3].age = 18;
// Sort the persons in the list and print them in order of increasing age:
bubblesort(family, Amoutfamily);
for(int i = 0; i < Amoutfamily; i++){
family[i].Print();
}
int findIndex = LinearSearch(family, Amoutfamily, 4);
if(findIndex >= 0){
family[findIndex].Print();
}
else{
cout << "Found no person with the specified age." << endl;
}
cin.get();
return 0;
}