• Advertisement
Sign in to follow this  

[SOLVED] c++ sorting problem

This topic is 1936 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I have been working on this problem for a while.I am working on writing a program that asks the user to enter the number of pancakes eaten for breakfast by 10 different people. My question how do I modify this program so that it outputs a list in order of number of pancakes eaten by all 10 people. I am using a bubble sort to sort the array of values.I also want to output which person ate the least and most number of pancakes, which I have figured out.

I want the program to output the following list.

Person 4: ate 10 pancakes.
Person 3: ate 7 pancakes.
Person 8: ate 4 pancakes.
...
Person 5: ate 0 pancakes.

Here is the code I am using.

[source lang =c++]

#include <iostream>
#include <algorithm>
using namespace std;
int array[10];
int main()
{
for(int i=0;i< 10;i++)
{
cout << "Enter number of pancakes eaten: ";
cin >> array;
}
for(int i=0; i<10; i++)
{
for(int j=0;j<i;j++)
{
if(array<array[j])
{
int temp = array;
array=array[j];
array[j]=temp;
}
}
}
int size=10;
int position = 0;
int result = -1;
int target=array[9];
while(result==-1 && position < size)
{
if(array[position] == target)
{
result = position;
}
position++;
}

cout << endl;
cout << "Person " << result << " ate " << array[result] << " the most pancakes." << endl;
cout << endl;
size=10;
position=0;
result = -1;
target = array[0];
while(result==-1 && position < size)
{
if(array[position] == target)
{
result = position;
}
position++;
}
cout << endl;
cout << "Person " << result << " ate " << array[result] << " the least pancakes." << endl;
cout << endl;
for (int j=0; j< 10; j++)
{
cout << "Person " << j << " ate " << array[j] << " pancakes." << endl;
}
int test;
cin >> test;
return 0;
}

[/source]

Share this post


Link to post
Share on other sites
Advertisement
I cannot see the whole code.

I didn't really get your problem. Getting min/max is easy when you have it sorted.
So: currently you sort the array of numbers (called array, bad thing, I have no idea what it should contain. neither do you after a few weeks), containing the number of pancakes i presume. Your problem is that you then cannot link the number to the person anymore?

If you are interested, have a look at the insertion sorting algorithm, it is more usable than bubble sort, if you want to implement a sorting algorithm yourself.

Share this post


Link to post
Share on other sites
#include <iostream>
#include <algorithm>
using namespace std;
int array[10];
int main()
{
for(int i=0;i< 10;i++)
{
cout << "Enter number of pancakes eaten: ";
cin >> array;
}
for(int i=0; i<10; i++)
{
for(int j=0;j<i;j++)
{
if(array<array[j])
{
int temp = array;
array=array[j];
array[j]=temp;
}
}
}
int size=10;
int position = 0;
int result = -1;
int target=array[9];
while(result==-1 && position < size)
{
if(array[position] == target)
{
result = position;
}
position++;
}

cout << endl;
cout << "Person " << result << " ate " << array[result] << " the most pancakes." << endl;
cout << endl;
size=10;
position=0;
result = -1;
target = array[0];
while(result==-1 && position < size)
{
if(array[position] == target)
{
result = position;
}
position++;
}
cout << endl;
cout << "Person " << result << " ate " << array[result] << " the least pancakes." << endl;
cout << endl;
for (int j=0; j< 10; j++)
{
cout << "Person " << j << " ate " << array[j] << " pancakes." << endl;
}
int test;
cin >> test;
return 0;
}

here is the whole code.

Share this post


Link to post
Share on other sites
Make a structure that contains all the information you need.

struct person {
int number;
int pancakes;
};

Sort an array of persons based on the pancakes-field.

Share this post


Link to post
Share on other sites

here is the whole code.

Please use [code ][/code ] tags (without the space). [source ] tags are broken on GameDev.net. Also, I think you're OP is better then they have been in the past, so good job on improving the quality. Just one more thing to do to improve it: you didn't explain exactly what the problem is. You did well explaining what you wanted to do and you're end goal, but it would've helped had you been clear about why it's not working, and what is currently happening.

Anyway... good to see you're coming back to this pancake problem of yours. As Brother Bob has pointed out, you need to pair the person with the number of pancakes they ate. If you don't pair them together, it's impossible to know exactly who ate how many pancakes.

Share this post


Link to post
Share on other sites
thanks corn, well the problem is that I am trying to sort the number of pancakes eaten not the person who has eaten them.I am sorry I am having difficult time explaining the problem.I will study up on oop and structs/classes.

Share this post


Link to post
Share on other sites
You should really learn to describe your problem better. If you can't explain it to humans, there is little hope of being able to explain the solution to a computer.

Perhaps you could give us an example of input and the expected output?

Share this post


Link to post
Share on other sites
The output should look like this:

Person 4: ate 10 pancakes.
Person 3: ate 7 pancakes.
Person 8: ate 4 pancakes.
...
Person 5: ate 0 pancakes.

The input looks like this:
for(int i=0; i<10;i++)
{
cout << "Enter the number of pancakes eaten: ";
cin >> array;
}

I can populate the array just fine, I am having minor in sorting the number of pancakes ate.

Share this post


Link to post
Share on other sites

Perhaps you could give us an example of input and the expected output?

And the actual (incorrect) output, so it's clear what the problem is.

Share this post


Link to post
Share on other sites
I think we all understood the problem just fine. You are not sorting numbers of pancakes; you are sorting people based on how many pancakes they ate. Brother Bob's suggestion is the easiest solution.

Share this post


Link to post
Share on other sites
The C++ standard library has (among other things) a very powerful toolbox of template tools that compliment each other.
The template tools are divided into three areas: Containers, Algorithms, and Iterators.

Containers hold your data, Iterators access your data, and Algorithms operate on your date.
(Algorithms use Iterators to access the data held in the Containers)

This is what Brother Bob is talking about when he said:

Make a structure that contains all the information you need.

struct person {
int number;
int pancakes;
};

Sort an array of persons based on the pancakes-field.


The container you want to use, is probably std::vector. std::vector is a array that can be resized easily, and is the default "go to" container you mostly want to use, unless you are trying to do something specific, and until you know the pros and cons of the other containers. (Each container, including std::vector, has tradeoffs - these tradeoffs are important to learn, but when in doubt, std::vector is usually a safe bet).

The iterator being used in this case is happening behind the scenes, so you don't need to worry about it. But if you're curious, it's a random-access iterator. (You'll learn more about these in the future, so don't worry if you don't understand it right now - I didn't bothered looking at them for years, and the fine details of how iterators work internally can be mostly ignored until later. Containers are more important, and Algorithms also. Understanding iterators helps you understand how Algorithms and Containers work, but aren't required knowledge to use them).

The algorithm you want to use in this case is std::sort. std::sort takes a range of elements* in a container, and sorts them in order from least to greatest. Ofcourse, what's "least" or "greatest" depends on the type of data given... data is expected to be able to provide their own comparison functions, or else a comparison function has to be passed to std::sort. Ints have built-in comparison functions (< > != ==, etc...).

*An 'element' is a fancy name that means "a piece of data a container holds". Like an array, myVector[0] accesses the first element in the container.

So, using std::vector to hold our pancake-eating heroes, and using std::sort to sort them by the number of pancakes eaten, we get this code:
struct Person
{
int id; //The number used to identify the person.
int pancakes; //The number of pancakes eaten.
};
bool PersonPancakeCompare(const Person &personA, const Person &personB)
{
//If personA is less than personB, return true.
//Here, we're measureing by number of pancakes eaten.
return (personA.pancakes < personB.pancakes);
}

int main()
{
std::cout << "How many people are eating pancakes?\n"
<< "Num people: ";

int numPeople = 0;
std::cin >> numPeople;

//A std::vector container of the 'Person' struct.
//The vector is currently empty (we haven't added anyone yet).
std::vector<Person> people;

for(int i = 0; i < numPeople; i++)
{
Person person;
person.id = i; //Keep track of what number this person is.

std::cout << "How many pancakes did person " << (i+1) << " eat?\n"
<< "Pancake count: ";

std::cin >> person.pancakes;

//Add the person to the end of the std::vector.
//push = "add to", back = "the back of the vector".
//push_back(person) = "add to the back of the vector, the data in 'person'".
people.push_back(person);
}

//Use std::sort algorithm on the std::vector, from the vector's begin()ing, to the vector's end().
//Since the struct "Person" is a new type of struct, we need to tell std::sort what makes a 'Person' less-than or greater-than
//another Person. So we provide our own comparison function, "PersonPancakeCompare()" to tell std::sort() how to compare 'Person' variables.
std::sort(people.begin(), people.end(), PersonPancakeCompare);

//Now, we can print out the results.
std::cout << "\n\n-------------------------\n"
<< "Results:" << std::endl;

//Loop over the entire (already-sorted) vector, and print out each person.
for(int i = 0; i < people.size(); i++)
{
Person &person = people;
std::cout << "Person " << (person.id + 1) << " ate " << person.pancakes << " pancake(s)!" << std::endl;
}

return 0;
}


std::sort() isn't a bubble sort, though, because in this situation a bubble sort isn't needed. If however, this is a homework question, and the teacher specified "use a bubble sort", then this code doesn't qualify and would fail the teacher's requirement. But ofcourse this isn't a homework question, is it? Because if it is, you conveniently forgot to mention it in your original post. wink.png

Share this post


Link to post
Share on other sites
wow that is alot to learn,I have decided to rewrite my program using classes and member funcitions,and the heap,it is some good practice for me,I am also using pointers.I like to oop techniques when I can but I have tenous understanding of pointers, but I am doing some studying up on them.here is the code I am using.

#include <iostream>
using namespace std;
int *pancakes = new int[10];
int *pancakes_one = new int[10];
int *pancakes_two = new int[10];
class Person
{
public:
void sort_pancakes(int*);
void num_pancakes(int*);
void output_pancakes(int*);
private:
int number;
int pancakes;
int panckes_one;
int pancakes_two;
};
void Person::num_pancakes(int *pancakes)
{
for(int i=0; i < 10; i++)
{
cout << "Enter number of pancakes eaten: ";
cin >> pancakes;
}
}
void Person::sort_pancakes(int *pancakes_one)
{
for(int i=0; i<10;i++)
{
for(int j=0;j<i;j++)
{
if(pancakes_one<pancakes_one[j])
{
int temp = pancakes_one;
pancakes_one = pancakes_one[j];
pancakes_one[j] = temp;
}
}
}
}
void output_pancakes(int *pancakes_two)
{
for(int k=0; k<10;k++)
{
cout << "Person " << k << " ate " << pancakes_two[k] << " pancakes." << endl;
}
}
int main()
{
Person pancake;
pancake.num_pancakes(pancakes);
pancake.sort_pancakes(pancakes_one);
pancake.output_pancakes(pancakes_two);
int test;
cin >> test;

return 0;
}


I am however getting a linker error:
LINK : C:\Users\phil\Desktop\size\Debug\size.exe not found or not built by the last incremental link; performing full link
1>size.obj : error LNK2019: unresolved external symbol "public: void __thiscall Person::output_pancakes(int *)" (?output_pancakes@Person@@QAEXPAH@Z) referenced in function _main
1>C:\Users\phil\Desktop\size\Debug\size.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

I have traced the problem to the "pancake.output_pancakes(pancakes_two);"
line of code.
something is wrong in my member function, I think??

Share this post


Link to post
Share on other sites
Yep, you made your member function forgett to be a member-function, and declared it just as a regular function. smile.png
void output_pancakes(int *pancakes_two)

Should be:
voidPerson::output_pancakes(int *pancakes_two)

For your:
int *pancakes = new int[10];
int *pancakes_one = new int[10];
int *pancakes_two = new int[10];


It really is much better if you use vectors:
std::vector<int> pancakes(10, 0); //Ten ints initialized to 0.

But even if you don't use vectors, you shouldn't use dynamic (heap) memory here. Stack is better, whenever you can:
int pancakes[10] = {0};

One of the reasons is if you use heap memory, it's easy to forget to release it when finished... like in your code. You new'd it, but forgot to call delete. Every new must also have a delete, but it's better code to avoid calling new and delete directly, and let objects manage their own lifetimes by putting them on the stack. (RAII)

In modern C++, even using dynamic/heap memory should be done through manager classes 99% of the time. (std::smart_ptr, std::weak_ptr, std::unique_ptr, etc... if you are using the latest standard - which if you aren't now, you soon will be - so it's good to get that into your mind ahead of time).

To summarize these tips for success in C++:

  • Whenever possible, prefer stack over heap. They are safer, and declares intent better.
  • Whenever possible, prefer references over pointers. They are safer, and declares intent better.
  • Whenever possible, prefer smart pointers over raw pointers for dynamic memory. They are safer, and declare intent better.
  • Whenever possible, prefer pancakes over waffles. They are tastier, and leave syrup in your beard for later snacking.

Share this post


Link to post
Share on other sites
I have decided to finish my sorting problem,I have made some changes to my code,I am using two arrays to store pancakes and people,I then sort the values inputted,by using a bubble sort,I then output the values.the hard part is getting the values to parallel each other. In other words I only want the pancakes to be sorted but I want the persons to be related to each pancake value.Here is my code:

#include <iostream>
using namespace std;
int pancake[11];
int person[11];
int main()
{
for(int i=1;i<=10;i++)
{
cout << "Enter number of pancakes eaten: ";
cin >> pancake;
person=i;
}
for(int i=1; i<=10; i++)
{
for(int j=1;j<=i;j++)
{
if(pancake>pancake[j])
{
int temp = pancake;
pancake=pancake[j];
pancake[j]=temp;
}
}
}
for(int i=1; i<=10; i++)
{
for(int j=1;j<=i;j++)
{
if(person>person[j])
{
int temp = person;
person=person[j];
person[j]=temp;
}
}
}
for(int i=1; i<=10;i++)
{
cout << "Person " << person << " ate " << pancake << " pancakes." << endl;
}
int test;
cin >> test;
return 0;
}


I really want to finish this project.

Share this post


Link to post
Share on other sites
If you have two arrays you can't sort them independently. That will give a sorted pancake array and a sorted person array without preserving the relation between them. If you want to sort both of them by the number of pancakes then sort the pancakes, but every time you swap two elements of the pancake array swap the corresponding members of the person array.

Share this post


Link to post
Share on other sites
This is a question I have asked people in interviews. There are basically three solutions:

  1. Create an array of structs that contain both the person and the pancakes (Brother Bob's solution).
  2. Sort the array of pancakes, but swap elements in the array of persons in parallel (SiCrane's solution).
  3. Create an array of indices initialized to {0,1,2,3,...} and sort it by comparing the entries in the array of pancakes.

Solution 3 is a good choice if there are multiple arrays that you need to sort in parallel or if swapping the entries is expensive.

Share this post


Link to post
Share on other sites
I have decided to rework my code,but now it won't sort my array and output it.

#include <iostream>
#include <stdlib.h>
using namespace std;
int arr[10]={0};
void bubbleSort(int arr[], int n) {
bool swapped = true;
int j = 0;
int tmp;
while (swapped) {
swapped = false;
j++;
for (int i = 0; i < n - j; i++) {
if (arr > arr[i + 1]) {
tmp = arr;
arr = arr[i + 1];
arr[i + 1] = tmp;
swapped = true;
}
}
}
}
int main()
{
for(int i=0;i<10;i++)
{
cout << "Enter number of panckes eaten: ";
cin >> arr;
}
int n=10;

for(int j=0;j<10;j++)
{
void bubbleSort(int arr[],int n);
}

for(int i=0; i<10;i++)
{
cout << "Person " << i << " ate " << arr << " pancakes." << endl;
}

system("pause");
return 0;
}


i did this to better understand functions

Share this post


Link to post
Share on other sites
To call a function, you have to pass in parameters.

"void bubbleSort(int arr[],int n);" is used to create a function. You never actually use the function.

Your "bubbleSort()" function won't know what array to use, and won't know what 'n' is set to, until you actually pass it parameters like this:
bubbleSort(myArray, 10);

Further, you don't need to call the function 10 times (just once in your specific example), so it doesn't need to be in the for() loop.

[hr]

When a function defines parameters, those parameters are variables. When you pass in variables to a function call, you are saying "Set the function's parameters are to the value of the variables I'm passing in to it".

The parameters do not need to have the same name as the variables being passed in. (You are passing in the data your variables hold, not the variables themselves).

Likewise, when a function returns a value, it's returning the data that you can then assign to a different variable.

Example: (this is important to understand)
int myFunction(int parameterA, int parameterB)
{
return (parameterA + parameterB);
}

int main()
{
int result1 = myFunction(15, 20); //Passing in data from temporary variables without names that are set to 15 and 20.
std::cout << "result1: " << result1 << std::endl;

int var1 = 1004;
int var2 = 230;

int result2 = myFunction(var1, var2); //Passing in data held in variables. (The variables aren't passed in, just *copies* of the data they hold)
std::cout << "result2: " << result2 << std::endl;

int result3 = myFunction(var2, 23000); //Passing in data from temporary and non-temporary variables.
std::cout << "result3: " << result3 << std::endl;

system("pause");
return 0;
}


A number like "45" just floating in your code can be thought as (but isn't exactly) an unnamed temporary variable with the value of 45. These are called 'literals'.

When you go:
int myVar = 45;
You are saying, "*copy* the data '45' into the variable 'myVar'".

When you go:
int myOtherVar = myVar;
You are saying: "*copy* the data held in myVar into the variable 'myOtherVar'".

If you have the code:
void myFunction(int param1, int param2);

int main()
{
int myVar = 45; //Holds data equal to the value of '45'.
int myOtherVar = myVar; //Also holds data equal to the value of '45'.

myFunction(myVar, myOtherVar);

return 0;
}


On the line that goes:
myFunction(myVar, myOtherVar);
You are saying "*copy* that data of 'myVar' into myFunction's variable 'param1'. Also, *copy* that data held in 'myOtherVar' into the variable 'param2'."

It is exactly the same as going like this:
int param1 = myVar;
int param2 = myOtherVar;

Except that 'param1' and 'param2' can only be used inside myFunction().

You are *copying* the data, not the variables themselves. (Variables hold data. It's the data you are passing around, not the containers holding them). Edited by Servant of the Lord

Share this post


Link to post
Share on other sites
I finallly figured out my sorting program.thanks for all the help.

[mod edit] merged with your original thread Edited by Hodgman

Share this post


Link to post
Share on other sites

ok, what was it? how did you solve it?

His original thread can be found here. I'm not sure why he made this thread... perhaps a mistake.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement