# Sort function

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

## Recommended Posts

I have a newbie question: I want to make a sort function that have unlimited number of parameters to be given. For example I want to sort 5 numbers 3,4,5,19,2 (form another function) and should be: "sorting (5,3,4,5,19,2);" I've tryed to do it but It keeps giving me errors. So whats wrong with the nex code ?
#include <iostream>
#include <stdlib.h>

using namespace std;
int n,i,j,man;

int sorting(int n,int v[0],...) {
for (i=0;i<n;i++) {
for (j=i+1;j<n;j++) {
if (v>v[j]) {
man=v;
v=v[j];
v[j]=man;
}
}
}

for (i=0;i<n;i++) {
cout<<v;
cout<<endl;
}
system("PAUSE");
}

int main() {
sorting(4,1,7,3,6); // That should sort "(4," 4 numbers that are 1,7,3,6)
}
//And I dont want to use a sort function from internet because I do this for my own learning process
Thanks


##### Share on other sites
You're main function should be:

int main() {

int array[4] = {1, 7, 3, 6};
sorting(4,array); // That should sort "(4," 4 numbers that are 1,7,3,6)

}

##### Share on other sites
Thanks man. It worked. Also I've learned something new about arrays. :)

##### Share on other sites
You're using variable arguments lists, which have some specific syntax in C++. Have a look at this page for the proper syntax; the va_* stuff can give you a little bit more safety and eliminate the need for the count parameter.

However, I would recommend against using variable argument lists. It is easy to pass arguments to your function that are not numbers, which can cause all manner of horrible bugs. The "..." system is extremely unsafe and it is a bad habit to get into using it.

Instead, you can use something like a std::vector to hold your set of numbers, and have the sort() function use that:

void sorting(std::vector<int>& numbers){  // Do sorting here  // The parameter is a reference to a vector holding ints  // This means that when we modify the parameter, we're  // really modifying the original variable that we got  // passed from main.}int main(){  std::vector<int> numbers;  numbers.push_back(1);  numbers.push_back(7);  numbers.push_back(3);  numbers.push_back(6);  sorting(numbers);  // Print out the contents of numbers}

Then you can use the built-in .size() function on the vector to know exactly how many elements there are. You also know that every entry in the vector will be a number (an int, in this case) because the compiler won't allow you to add other types of data. Even better still, the vector will automatically take care of handling any memory shuffling that needs to be done.

As one final bonus, once you've learned some sorting methods on your own, you can simply switch over to using the std::sort function, and never have to worry about sorting again [smile]

##### Share on other sites
ok! Thanks ! I'll try that to for sure! :)

##### Share on other sites
I was the anonymous poster by the way. Anyway, you can do your main function like this aswell, which makes it easier to update:

int main()
{
int array[] = {1, 3, 8, 2}; //as an example
sorting(sizeof(array), array); //takes the size of the array as the first parameter
}

But it is better to use ApochPiQ's method.

##### Share on other sites
Yes, that for automaticaly detection on how much numbers are. :) Also after that I should try ApochPiQ way wich is a litle dificult for me to understand! Thanks again to all.

##### Share on other sites
Bu the sizeof() wont return me the number of indices of the arrays, right ?

##### Share on other sites
Oh yea, sorry my mistake, forget that last post.

##### Share on other sites
sizeof(array) / sizeof(int) will give you the number of elements in the array.

##### Share on other sites
Ok, it worked. Thanks. I will also hang around here with other newbie questions later.

##### Share on other sites
If you're interested in seeing what algorithms there are out there besides bubblesort, then let us know. I have tons of links to other algorithms and sorting tutorials.

##### Share on other sites
ok. Let me see...

##### Share on other sites
Here's a list for you to google:
RadixSort          IntroSort         QuickSort            ProportionExtendSortFlashSort          SmoothSort        FibonacciHeapSort    WeakHeapSortHeapSort           NaturalMergeSort  MergeSort            ShellSortHybridCombSort     CombSort          BinaryTreeSort       BitonicSortShearSort          StrandSort        BinaryInsertionSort  InsertionSortDualSelectionSort  SelectionSort     BingoSort            SeveralUniqueSortShakerSort         ElevatorSort      BubbleSort           OddEvenSortGnomeSort          ExactSort
I guess CombSort would be good for you to look into because it's a logical extension to bubbleSort, is generally quite fast, and is a very compact algorithm.

##### Share on other sites
Ooo! So many! Thanks a lot!

##### Share on other sites
As I saw on that site from you Built In C++ sort is the fastest, right ? I'm learning C++ especialy for game programming later. So I should care about speed, right ?

##### Share on other sites
another one I didn't see mentioned: Bucketsort

Which is the absolute best for large amounts of a smallish known range (ie: if all numbers are 0 to 100) of integers (or a known distribution which can be broken down into array indicies easily).

example: if we have these numbers to sort: 1, 3, 2, 5, 2, 6, 5, 3, 10, 2, 9, 1, 7

we set up an array "bucket[11]" containing all zeros
then we iterate through the original list of numbers to sort and do this
for(int i = 0;i<(int)((sizeof(numbersToSort)/sizeof(int));i++){  bucket[numbersToSort]++;}

once we're done that we simply iterate through the bucket and do this:
int k = 0;for(int i = 0;i<11;i++){  while(bucket>0){    numbersToSort[k] = i;    bucket--;    k++;  }}

My apologies for any mistakes, I did this quick from memory and didn't try it out.

You can set it up to have an offset as well if you have items ranging from 30 to 200 by simply zeroing out the 30 when you set up the bucket array and then adding it to the value when you put the info back into the real array. Ultimately you'll probably have to do an initial search for the min and max if you don't already know them, then you'll have to iterate once more through the thing to set up the bucket then you iterate through the bucket. You can also set it to only do a bucket sort if the range is under a certain value and the number of elements is small and then resort to a different sort if that is the case. The reason I say you may want to do the check for uncertain values as opposed to just using another method is that this one can do it in such a small amount of time compared to many others that the small performance hit of the search (when it might let you bucket sort 50% of the time, let's say) could vastly outweigh the hit of doing a different algorithm...

But it all depends on the data.

And yes, you should probably use the built in sorts.

[Edited by - M2tM on January 4, 2006 3:18:56 PM]

##### Share on other sites
Quote:
 Original post by boboSAs I saw on that site from you Built In C++ sort is the fastest, right ? I'm learning C++ especialy for game programming later. So I should care about speed, right ?

The built-in sort has been worked upon for years by clever compiler-writers to give you the best general-purpose performance possible. And it's already *done for you* - unless you've (a) already determined it's not fast enough and (b) know a significant amount of stuff that makes your data "special" (so that you can take advantage of that knowledge to write a specific sort that will be faster for your stuff), using it is a no-brainer.

You should keep in mind the interface that this function uses, too. There is really hardly ever a good reason to use variadic functions in C++, and when your data is always going to come from some container anyway... ugh.

#include <iostream>int main() {  int data[] = {1, 7, 3, 6};  std::sort(data, data + sizeof(data) / sizeof(int));  // here "data" is used as a pointer to the beginning of the array, and a  // pointer can be used as an "iterator" which is what std::sort expects.  // It wants two of these, to indicate the beginning and end of the range - the  // "end" should actually be one *past* the end, which is actually more  // convenient for us - it's (number of elements) past the beginning.  // We use sizeof magic to get the array size, and then increment the pointer  // (that effectively re-multiplies by sizeof(int) when calculating an  // address) to get the end pointer.}

• 10
• 12
• 10
• 10
• 11