### generic sorting algorithm , not using sort()

Implement a generic sorting algorithm i.e. the input array may contain int, double or structure values , or any type of data defined by user ?

The comparator will be defined by user .
I thought to modify C++ sort , but stuck on the comparator .

I want to implement my own function , not using sort() of C++ .

I came up with the below code but it is genereting errors :

 ``12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485`` `````` #include #include #include #include #include using namespace std; class Person { public: // default constructor Person() : age(0) {} Person(int age, string name) { this->age = age; this->name = name; } int age; string name; }; // function object struct GreaterAge { bool operator()(const Person& a, const Person& b) { if(a.age == b.age) return a.name < b.name; return a.age > b.age; } }; template void Merge(T *a, int p, int q, int r , bool compare(const T& ,const T& )) { int i, j, k; const int n1 = q-p+1, n2 = r-q; int L[n1]; int R[n1]; for(i=0;i=n2 || (iR[j] { a[k] = R[j++]; } } } template void Merge_Sort(T *a, int p, int r , bool compare(const T& ,const T& )) { if(p
The merge functions are supposed to look like this:
 ``12`` ``````template void Merge(T *a, int p, int q, int r , TCompare compare)``````

Line 79: you cannot provide a class name just an object:
`Merge_Sort(arr,0,4,GreaterAge()); // Note () `

Line 40/41 are `int`, but should be `T`
yes, it worked , thanks for the fix.

Just wanted to know how to use iterators in templates , so that functions can be generic , for example consider input is a `vector` rather than an `array`.

Also , what if user do not define a `compare()` function ? `std::sort()` can handle this . How can it be achieved ?
std::sort has two versions (overloads). One takes comparator and the other does not. The latter is hardcoded to use operator< (of T).
last question : how to use iterators in templates , so that functions can be made generic , for example consider input is a vector instead of an array.
Last edited on
The problem is on line 40/41. You need to deduce the type of the data.
So you need a third parameter for the type:

 ``12`` ``````template void Merge_Sort(TIterator a_begin, TIterator a_end, int p, int q, int r , TCompare compare)``````

Call it like so:

 ``123`` ``````std::vector v; ... Merge_Sort(v.begin(), v.end(),0,4,GreaterAge());``````

You might omit the `r` parameter because you might calculate it from the iterators. Not all iterator types allow this though
Topic archived. No new replies allowed.