Jump to content

  • Log In with Google      Sign In   
  • Create Account


[SOLVED] c++ sorting problem


Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.

  • You cannot reply to this topic
25 replies to this topic

#1 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 22 September 2012 - 02:58 PM

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[i];}for(int i=0; i<10; i++){ for(int j=0;j<i;j++) { if(array[i]<array[j]) { int temp = array[i]; array[i]=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]

Sponsor:

#2 Bluefirehawk   Crossbones+   -  Reputation: 1190

Like
0Likes
Like

Posted 22 September 2012 - 03:07 PM

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.
Project: Project
Setting fire to these damn cows one entry at a time!

#3 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 22 September 2012 - 03:15 PM

#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[i];
}
for(int i=0; i<10; i++)
{
for(int j=0;j<i;j++)
{
if(array[i]<array[j])
{
int temp = array[i];
array[i]=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.

#4 Brother Bob   Moderators   -  Reputation: 7404

Like
3Likes
Like

Posted 22 September 2012 - 03:22 PM

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.

#5 Cornstalks   Crossbones+   -  Reputation: 6882

Like
0Likes
Like

Posted 22 September 2012 - 03:26 PM

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.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#6 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 22 September 2012 - 03:37 PM

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.

#7 Álvaro   Crossbones+   -  Reputation: 10594

Like
0Likes
Like

Posted 22 September 2012 - 03:46 PM

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?

#8 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 22 September 2012 - 03:55 PM

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];
}

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

#9 Cornstalks   Crossbones+   -  Reputation: 6882

Like
0Likes
Like

Posted 22 September 2012 - 03:55 PM

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.
[ I was ninja'd 71 times before I stopped counting a long time ago ] [ f.k.a. MikeTacular ] [ My Blog ] [ SWFer: Gaplessly looped MP3s in your Flash games ]

#10 Álvaro   Crossbones+   -  Reputation: 10594

Like
0Likes
Like

Posted 22 September 2012 - 04:49 PM

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.

#11 Servant of the Lord   Crossbones+   -  Reputation: 14848

Like
3Likes
Like

Posted 22 September 2012 - 09:06 PM

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[i];
	    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. Posted Image

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.

[Fly with me on Twitter] [Google+] [My broken website]

All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.                                                                                                                                                       [Need free cloud storage? I personally like DropBox]

Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal


#12 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 22 September 2012 - 10:30 PM

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[i];
}
}
void Person::sort_pancakes(int *pancakes_one)
{
for(int i=0; i<10;i++)
{
  for(int j=0;j<i;j++)
  {
   if(pancakes_one[i]<pancakes_one[j])
   {
    int temp = pancakes_one[i];
    pancakes_one[i] = 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??

#13 Servant of the Lord   Crossbones+   -  Reputation: 14848

Like
4Likes
Like

Posted 22 September 2012 - 11:15 PM

Yep, you made your member function forgett to be a member-function, and declared it just as a regular function. Posted Image
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.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.

[Fly with me on Twitter] [Google+] [My broken website]

All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.                                                                                                                                                       [Need free cloud storage? I personally like DropBox]

Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal


#14 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 01 October 2012 - 04:15 PM

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[i];
person[i]=i;
}
for(int i=1; i<=10; i++)
{
  for(int j=1;j<=i;j++)
  {
   if(pancake[i]>pancake[j])
   {
    int temp = pancake[i];
    pancake[i]=pancake[j];
    pancake[j]=temp;
   }
  }
}
for(int i=1; i<=10; i++)
{
  for(int j=1;j<=i;j++)
  {
   if(person[i]>person[j])
   {
    int temp = person[i];
    person[i]=person[j];
    person[j]=temp;
   }
  }
}
for(int i=1; i<=10;i++)
{
cout << "Person " << person[i] << " ate " << pancake[i] << " pancakes." << endl;
}
int test;
cin >> test;
return 0;
}

I really want to finish this project.

#15 SiCrane   Moderators   -  Reputation: 9119

Like
1Likes
Like

Posted 01 October 2012 - 05:06 PM

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.

#16 Álvaro   Crossbones+   -  Reputation: 10594

Like
3Likes
Like

Posted 01 October 2012 - 06:50 PM

This is a question I have asked people in interviews. There are basically three solutions:
  • Create an array of structs that contain both the person and the pancakes (Brother Bob's solution).
  • Sort the array of pancakes, but swap elements in the array of persons in parallel (SiCrane's solution).
  • 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.

#17 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 01 October 2012 - 08:05 PM

wow thanks for all the help

#18 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 02 October 2012 - 05:38 PM

I am going to try sicranes solution.

#19 phil67rpg   Members   -  Reputation: 755

Like
0Likes
Like

Posted 02 October 2012 - 08:56 PM

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[i] > arr[i + 1]) {
					    tmp = arr[i];
					    arr[i] = 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[i];
}
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[i] <<  " pancakes." << endl;
}

system("pause");
return 0;
}

i did this to better understand functions

#20 Servant of the Lord   Crossbones+   -  Reputation: 14848

Like
0Likes
Like

Posted 02 October 2012 - 10:08 PM

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.

 

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, 02 October 2012 - 10:23 PM.

It's perfectly fine to abbreviate my username to 'Servant' rather than copy+pasting it all the time.

[Fly with me on Twitter] [Google+] [My broken website]

All glory be to the Man at the right hand... On David's throne the King will reign, and the Government will rest upon His shoulders. All the earth will see the salvation of God.                                                                                                                                                       [Need free cloud storage? I personally like DropBox]

Of Stranger Flames - [indie turn-based rpg set in a para-historical French colony] | Indie RPG development journal





Old topic!
Guest, the last post of this topic is over 60 days old and at this point you may not reply in this topic. If you wish to continue this conversation start a new topic.



PARTNERS