I have an assignment in which I have to implement mergesort under these certain constraints that I'm having a hard time figuring it out. I can implement the merge sort function just fine just under constraints I am having alot of trouble.
For, this assignment, we are not allowed to alter any of the function parameters and are supposed to use the lessThan() function and the Key() function and by using these functions we are supposed to make the mergesort function work for any data type. The lessThan function basically compares two item types and returns true if the key of the first one is smaller than the second one and the key function just returns the key of an Item type. My idea was to use templates above each of the functions that uses Item instead of the typedef int Item, which would work but we are not supposed to do that. The typedef int Item is the main thing thats throwing me off, not sure how your supposed to make the function work for different type using this typedef. I have posted the code below.
For, this assignment, we are not allowed to alter any of the function parameters and are supposed to use the lessThan() function and the Key() function and by using these functions we are supposed to make the mergesort function work for any data type. The lessThan function basically compares two item types and returns true if the key of the first one is smaller than the second one and the key function just returns the key of an Item type. My idea was to use templates above each of the functions that uses Item instead of the typedef int Item, which would work but we are not supposed to do that. The typedef int Item is the main thing thats throwing me off, not sure how your supposed to make the function work for different type using this typedef. I have posted the code below.
// Do not rely on Item being an int. typedef int Item; int key(Item a); // Returns the key value for Item a. bool lessThan(Item a, Item B)/>/>; // Returns true if the key of Item a is less than the key of Item b. void merge_bitonic(Item* A,int p,int r); void mergesort_bitonic(Item* A,int p,int r);
#include"sorting.h"
#include<iostream>
using namespace std;
bool dir;
typedef int Item;
bool aord(string a){
if(a=="ascend")
return true;
if(a=="descend")
return false;
}
bool lessThan(Item a,Item B)/>/>;
void comp(Item a, Item b,bool dir){
Item temp;
if(dir==(a>B)/>/>){
temp=a;
a=b;
b=temp;
}
}
void merge_normal(Item* A,int p,int q, int r){
Item aux[r+1];
//This assumes that the two sub arrays are already sorted
int i=p;
int j=q+1;
for(int k=p;k<r+1;k++)
aux[k]=A[k];
for(int k=p;k<r+1;k++){
if(i>q)
A[k]=aux[j++];
else if(j>r)
A[k]=aux[i++];
else if(lessThan(aux[i],aux[j])==true)
A[k]=aux[i++];
else
A[k]=aux[j++];
}
}
void mergesort_normal(Item* A, int p,int r){
if(p<r){
int mid=p+(r-p)/2;
mergesort_normal(A,p,mid);
mergesort_normal(A,mid+1,r);
merge_normal(A,p,mid,r);
}
}