• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

which sorting strategy do you prefer? heap,sort... how to sort by calling a class?

harrylennox

Junior Member
Hi...

I am C++ beginner and I want to know something regarding to this:
how can I sort a 20 integers?
which sorting techniques do you prefer?
and
how can I sort a list of numbers by just calling a class to sort the user input numbers?

somebody could share about sorting codes and calling a class....

many thanks....





 
While not c++ specific, almost every programming language has some ability to implement the algorithms described here:

http://en.wikipedia.org/wiki/Sorting_algorithms

"Preference" usually is dictated by ease of implementation, and the workload of the algorithm (are you sorting a deck of cards, 1000 orders, or 500-billion entries in a database).
 
With a list of length 20, you are not going to notice a major difference in speed/efficiency between the usage of the popular sorting methods that SJP0tato linked to. Since this is the case, it would be logical to choose the one which is easiest to implement. The insertion sort method is rather painless:

void insertion_sort( apvector <int> &array)
{
int i, j, key, array_length=array.length( );
for(j = 1; j < array_length; j++) //Notice starting with 1 (not 0)
{
key = array[j];
for(i = j - 1; (i >= 0) && (array < key); i--) //Move smaller values up one position
{
array[i+1] = array;
}
array[i+1] = key; //Insert key into proper position
}
return;
}


 
The wikipedia article linked by SJP0tato covers most of the basics for the common sorting algorithm. Having said that, I believe STL provides some sorting algorithms for its container classes and unless you have an academic reason for learning how to make a sorting algorithm, its probably better to just use those are they are likely more efficient.

It is always good to familiarize yourself with the advantages/disadvantages of each sorting method however as they will sometimes come into play when deciding what you wish to sort.

@OP: What do you mean by "sort by calling a class"? Do you mean sorting a user defined class or using a class to sort some array?

Edit: Removed some erroneous statements.
 
I would probably just us the STL sort and not worry about how it is done. (especially for a problem this small)
 
I typically used the C++ function std::sort, but if you can't use the standard library for whatever reason, bubble sort is good enough for your purposes (or, if you must be fancy, go for comb sort).
 
Back
Top