The task is to implement a bubblesort function followed by a linearsearch aka "linsok" in my "familj" array. the array keeps both the name and the age, so i want to sort the array after their age and print it out. ive got the line search to work but now im stuck with the bubblesort.
The problem is that i dont know how to make my bubble sort code work for this code. so do i implement the second piece of code in this?
#include <iostream>
#include <string>
using namespace std;
class Person
{
public:
string namn;
int alder;
void skrivUt(string _namn, int _alder)
{
namn = _namn;
alder = _alder;
}
};
int linsok(Person* PersonArray, int key)
{
for (int i = 0; i < 4; i++)
{
if (PersonArray[i].alder == key)
return i;
}
return -1;
}
int main()
{
Person familj[4];
familj[1].skrivUt("Emma",23);
familj[3].skrivUt("Emilia",29);
familj[2].skrivUt("Johan",26);
familj[0].skrivUt("Timmy ",21);
int index = linsok(familj,22); //the age of the person im looking for.
if(index== -1)
cout << "Personen hittades ej!"; //person not found
else
//prints out the persons name and the index.
cout << "Personen heter " << familj[index].namn << " hen finns på index " << index << endl;
cin.get();
return 0;
}
This is the piece of bubble-sort code i used before and it works.
int p [] = {10,56,73,23,31,24,43};
int a = 6;
for (int i = 0; i < a; i++)
{
int nrLeft = a - i;
for (int j = 0; j < nrLeft; j++)
{
if (p[j] > p[j+1])
{
int temp = p[j];
p[j] = p[j+1];
p[j+ 1] = temp;
}
}
}
for(int i = 0; i < 7; i++)
cout << p[i] << endl;
cin.get();
It's likely that you want to convert this to a function that you pass your array of Person
objects to, along with the size of it, and then you just access the part that you want to compare. Since you'd be implementing it as a function, you can use it in the same way you use your linsok
function, although you'd probably want it to return the sorted array as opposed to an index.
Disclaimer for following code: Neither run nor compiled
Person* bubbleSort(Person* p, int size)
{
for (int i = 0; i < size; i++)
{
int nrLeft = size - i;
for (int j = 0; j < nrLeft; j++)
{
if (p[j].alder > p[j+1].alder)
{
Person temp = p[j];
p[j] = p[j+1];
p[j+ 1] = temp;
}
}
}
return p;
}
That's based off you sorting them by alder (which I guess is age? I don't speak Swedish(?)) You just need to provide the signature, and alter it based on your needs, but the basic idea is that you just change what you compare, and the data types.
Another way to do this is to return an int
or void
(But you should return an int to tell you if it was successful or not), and pass a pointer to the array, so Person**
in the signature, and operate directly on that array, but that's a little more difficult, and arguably bad practice, depending on use case.