Need some help
So, I need to use a mergesort to organize the names by alphabetical order and also the height ..
I am totally confused, I am having major difficulty with c++, the following is what I pieced together from an example in class, please help!
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
|
#include <iostream>
#include<vector>
#include <string>
#include "person.h"
void quicksort(person people[], int start, int end);
using namespace std;
int main()
{
const int num_people = 10;
person people[num_people];
people[0].name = "Mulan";
people[0].height = 157.5;
people[1].name = "Tiana";
people[1].height = 165;
people[2].name = "Aladdin";
people[2].height = 177.5;
people[3].name = "Esmeralda";
people[3].height = 170;
people[4].name = "Gaston";
people[4].height = 190;
people[5].name = "Donald";
people[5].height = 137;
people[6].name = "Daisy";
people[6].height = 135;
people[7].name = "Baloo";
people[7].height = 188;
people[8].name = "Goofy";
people[8].height = 185.5;
people[9].name = "Mary";
people[9].height = 167.5;
cout << "Unsorted:\n";
for (int i=0; i<num_people; i++)
{
cout << " " << people[i].name
<< "\t " << people[i].height << endl;
}
cout << "Sorted by height:\n";
for (int i=0; i<num_people; i++)
{
cout << " " << people[i].name
<< "\t " << people[i].height << endl;
}
//insert your mergesort function call here!!
// and dont forget to define what it does!!
cout << "Sorted alphabetically:\n";
for (int i=0; i<num_people; i++)
{
cout << " " << people[i].name
<< "\t " << people[i].height << endl;
}
return 0;
}
void quicksort(person people[], int start, int end) // Start = beginning index, end = ending index
{
if (start >= end)
return;
int pivot_index = ( end + start )/ 2;// Pivot index
int pivot_value = people[pivot_index];
vector<int> lesser, greater;
for (int i = start; i <= end; i++)
{
if ( i == pivot_index)
continue;
if (people[i] <= pivot_value)
lesser.push_back(people[i]);
else
greater.push_back(people[i]);
}
int j = start;
for (int i = 0; i<lesser.size();i++)
{
people[j] = float(lesser[i]);
j++;
}
people[j++] = float(pivot_value);
for (int i = 0; i<greater.size();i++)
{
people[j] = float(greater[i]);
j++;
}
quicksort(people, start, start+lesser.size()-1);
quicksort(people,start+lesser.size()+1, end);
}
|
Topic archived. No new replies allowed.