Question:
how to make a sort function of an array in c++?
anonymous
2010-01-25 09:42:17 UTC
i wrote this code that sorts an arary entered by the user. now i want to convert the sorting part in to a function and make main display the array sorted using the sort function.

// loop reciept
#include
#include
using namespace std;



int main()
{

float price[100];

int num=0, a;
int i, j;
int temp; // holding variable

cout << "Enter number of prices to be entered: ";
cin >> a;
cout << "\n";
for(int x=0;x {

cout << "Enter the price of the item "< cin >>price[num];

num++;
}



for (i=0; i< (a -1); i++)
{
for(j = (i+1); j < a; j++)
{
if (price[i] > price[j])
{
temp= price[i];
price[i] = price[j];
price[j] = temp;
}
}}
for(int x=0;x cout<





return 0;
}






thanks a lot
any input is valuable
Seven answers:
?
2010-01-25 09:50:30 UTC
Luckily, since you wrote the sorting already, making it into a function is as easy as writing a few lines of code. First, you need to type the prototype declaration in the beginning of your program. Name the function something easy to rememeber, like SortArray(). You're going to have to pass the array to the function because you can't use any variable inside a function that isn't declared inside that function. So when you write the actual function, you'll need to put SortArray(float &price[]). When you actually CALL the function in your main() you need to make sure you pass it the array so you'd write SortArray(price) (which passes the array price to the function when you call it). You'll also need to move the counting variables inside the function as well.
Chris C
2010-01-25 10:14:03 UTC
Well, you broke it up fairly well. There are a couple of issues I noticed with your code:

1) 'temp' variable is defined as 'int'. It should be the same type as you are storing in the array.

2) 'x' variable is defined 2 times. Although the compiler won't care about this, it's better to declare 'x' toward the top one time, and then simply reuse it.

3) You didn't include , which allows you to use a "swap()" function, that doesn't care what type the variable is, and you could then do away with the 'temp' variable. This one isn't required, but it makes the code a lot cleaner and easier to read.



Overall, you did a very good job!





I've included the changes below and I am sure you'll recognize what has been done.



// loop reciept

#include

#include

#include

using namespace std;



void sortIt(float price[], a)

{

   int i, j;



   for (i=0; i< (a -1); i++)

   {

      for(j = (i+1); j < a; j++)

      {

         if (price[i] > price[j])

            swap(price[i], price[j]);

      }

   }

}



int main()

{

   float price[100];



   int num=0, a;

   int x;



   cout << "Enter number of prices to be entered: ";

   cin >> a;

   cout << "\n";

   for(x = 0; x < a; x++)

   {

      cout << "Enter the price of the item " << num+1 << ": ";

      cin >> price[num];



      num++;

   }



   // Sort the array

   sortIt(price, a);



   for(x = 0; x < a; x++)

      cout<


   return 0;

}
Mantis
2010-01-25 10:05:16 UTC
Sure. Here's what you do.



1. Take the existing code and move it out of the function it's in

2. If the code is dependent on any variables in the main routine, pass those as parameters



So the function would look like this:



void SortArray(float array[], int arraySize) //pass in the array and the length of the array

{

..float swap = 0; //holding variable --only used here so I moved it from main



..for (i=0; i< (a -1); arraySize++)

..{

....for(j = (i+1); j < arraySize; j++)

....{

......if (array[i] > array[j])

......{

........swap= array[i];

........array[i] = array[j];

........array[j] = swap;

......}

....}

..}

}



(obviously, you'll want to remove the periods... that's just here for formatting in Yahoo Answers.)



You'd call this function from main() like this:



SortArray(price, a);



I left the cout call in main, as this is part of the use of the array, not the sorting of the array. When you re-use the array sort routine later you won't necessarily want to print out the sorted values.





You'll notice that I took the liberty of renaming a few variables in your function. Here are the reasons:



1. To demonstrate that the name of the variable in the function doesn't need to match the name in the caller. So the main calls the array 'Price' but I called it 'array' in the function. A lot of programmers new to C++ don't see this right away. It's legal to name them the same, but they are DIFFERENT copies of the value.



2. One goal of a function is to have something you can reuse. 'Price' is specific to what Main is doing and your sort function can sort any array of floats.



3. I strongly advise staying away from short names. C++ allows names as long as you like, and descriptive names are much easier to maintain later than short names. You'll forget what 'a' was in two weeks, let alone two years. Longer names like 'arraySize' fix that problem. Descriptive names are often called "self-documenting" because you don't need comments to say what they're fore. The variables x, y, and i are exceptions... they have specific roles that are already self-documenting. X and Y are coordinates, and i is a loop variable. j is often a loop variable as well. Use it if you like, but I find i and j confusingly similar to the eye. :)



4. Personal preference, I avoid 'temp' in final code. I often use the word 'temp' in code I insert for debugging and will remove later, so if I see a variable called 'temp' I assume it's not needed in the finished product. But that's just me.



Also, your swap variable above is an int, while the array is floats. You'll want to change that around or you'll not only be sorting the array but also rounding it! :)



Good luck, and let me know if you need further clarification.
Faerie
2010-01-25 11:18:24 UTC
Since your sort already works the way it should, the easiest thing to do would be to create a function that will return the array sorted.



Pseudocode:



float[] Sort(float p)

{

for (i=0; i< (a -1); i++)

{

for(j = (i+1); j < a; j++)

{

if (p[i] > p[j])

{

temp= p[i];

p[i] = p[j];

p[j] = temp;

}

}}

return p;

}



then call it like this:



price = Sort(price);

Then use your printing loop to display:

for(int x=0;x
cout<
anonymous
2010-01-25 09:51:56 UTC
void bubbleSort(int *array, int length)

{

int i, j, temp;

int test; /*use this only if unsure whether the list is already sorted or not*/

for(i = length - 1; i > 0; i--)

{

test=0;

for(j = 0; j < i; j++)

{

if(array[j] > array[j+1]) /* compare neighboring elements */

{

temp = array[j]; /* swap array[j] and array[j+1] */

array[j] = array[j+1];

array[j+1] = temp;

test=1;

}

} /*end for j*/

if(test==0) break; /*will exit if the list is sorted!*/

} /*end for i*/



}/*end bubbleSort*/
kushiner
2016-10-02 02:28:05 UTC
Array.sort C
?
2010-01-25 09:45:19 UTC
Just use qsort() - that's why it's there.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...