1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115
|
// Bubblesort.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
using namespace std;
//Klass: contain a person with name and age
class Person
{
public:
char* name;
int age;
//Metod: Sets the necessary info
void SetInfo(char* _name, int _age)
{
name = _name;
age = _age;
}
};
// Funktion: LinearSearch: Search for a person in a list
int LinearSearch(Person* personArray, int key)
{
for (int i = 0; i < 10; i++) //Go through the whole list
{
// Is it the number we are searching for?
if (personArray[i].age == key)
return i;
}
return -1; // Person were not found
}
// Function BubbleSort, sorting Person myList[] by age
void BubbleSort(Person* myList[], char* _name, int _age)
{
char* name = _name;
int age = _age;
int max = 9;
// The outer loop, going through all list
for(int i = 0; i < max; i++)
{
//Inner loop, going through element by element
int nrLeft = max - i; // To se how many has been gone through
for (int j = 0; j < nrLeft; j++)
{
if (myList[j] > myList[j+1]) // Compare the elements
{
// Change place
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;
}
}
}
// Write the list
for (int i = 0; i < 9; i++)
{
cout << myList[i] << "\n";
}
}
/*
void swap(Person &p, Person &q)
{
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;
}
*/
// Function: Main, start on program
int main()
{
//Create a list with persons and fill it:
Person myList[10];
myList[0].SetInfo("Charles", 22);
myList[1].SetInfo("Darwin", 21);
myList[2].SetInfo("Phytagoras", 23);
myList[3].SetInfo("Michelle", 65);
myList[4].SetInfo("Carl", 76);
myList[5].SetInfo("Cathrine", 54);
myList[6].SetInfo("Marielle", 25);
myList[7].SetInfo("Patrick", 85);
myList[8].SetInfo("Oliver", 48);
myList[9].SetInfo("Elinette", 52);
//Search for a person in the list
int index = LinearSearch(myList, 54);
//Write out searchresults
if(index == -1)
cout << "Person wasn´t found!";
else
cout << "The person you are looking for is named" << myList[index].name << " and is on index " << index << "\n\n";
BubbleSort(myList);
cin.get();
return 0;
};
|