universal sorting algorithm

Nov 20, 2012 at 10:58pm
void Swap(T& i, T& j){
T Buff = i;
i = j;
j = Buff;
}
// universal sorting algorithm
template <class T>
void Sort(T A[], int Number){
for(int i = 0; i < Number; i++){
for(int j = 1; j < Number; j++){
if(A[i] > A[i-1]){
Swap(A[i], A[i-1]);
}
}
}
}
void main(){
int B[6] = {5,32,6,2,65,3};
Sort(B,6);
char C[6] = {'a','d','f','s','e','h'};
Sort(C,6);
}
//trying to create a universal sorting algorithm but not sure where to go from here.
Nov 20, 2012 at 11:00pm
"Universal sorting algorithm" is std::sort.:)
Nov 20, 2012 at 11:08pm
C++ already has a couple of generic sorting functions, as vlad pointed out, and it also has a generic swapping function.
http://cplusplus.com/reference/algorithm/swap/
http://cplusplus.com/reference/algorithm/sort/

If you want to write you own, check these for inspiration:
http://en.wikipedia.org/wiki/Sorting_algorithm
http://en.wikibooks.org/wiki/Algorithm_implementation/Sorting
Nov 20, 2012 at 11:29pm
I suggest you to realize the selection sort. It is intuitively more understandable.
Nov 20, 2012 at 11:37pm
ok thankyou i will look into all of these suggestions right now. also are there any errors that you can see right off the back or does it look good up until this part.
Nov 21, 2012 at 8:11am
Well, you forgot template <typename T> before void Swap(T& i, T& j) {.
And like I said, it doesn't make sense not using std::swap() from the algorithm header.

Then inside Sort() you have two for()'s with an i and a j, but you never use the j.

Finally, you write void main(). Modern C++ requires int main().
(Also, main() is a special case, so even if it has a return type int, you aren't required to return anything.)

1
2
3
4
int main()
{
    // return 0; // optional, but only for main()
}

Topic archived. No new replies allowed.