In: Computer Science
Write a program in which define a templated class mySort with private data members as a counter and an array (and anything else if required). Public member functions should include constructor(s), sortAlgorithm() and mySwap() functions (add more functions if you need). Main sorting logic resides in sortAlgorithm() and mySwap() function should be called inside it. Test your program inside main with integer, float and character datatypes.
In case of any query do comment. Please rate answer. Thanks
Note: There was nothing mentioned for the usage of counter. If you need anything further do let me know.
#include <iostream>
using namespace std;
template <typename T>
//class my sort
class mySort {
private:
int counter;
T *array; //array to hold elements
int numberOfElements;
public:
mySort(T arr[], int numberOfElements);
void sortAlgorithm();
void mySwap(T&x,T&y);
void displayData();
};
//constructor
template <typename T>
mySort<T>::mySort(T arr[], int number) {
array = new T[number];
numberOfElements = number;
counter =0;
for(int i = 0; i < numberOfElements; i++)
array[i] = arr[i];
}
//myswap method implementation
template <typename T>
void mySort<T>::mySwap(T&x,T&y)
{
T temp=x;
x=y;
y=temp;
}
//sortAlgorithm implementation
template <typename T>
void mySort<T>::sortAlgorithm()
{
for (int i = 0; i < numberOfElements - 1; i++)
for (int j = numberOfElements - 1; i < j; j--)
if (array[j] < array[j - 1])
mySwap(array[j], array[j - 1]);
}
//method to display data
template <typename T>
void mySort<T>::displayData() {
for (int i = 0; i < numberOfElements; i++)
cout<<" "<<array[i];
cout<<endl;
}
int main() {
//test with integer data
int arrInt[5] = {12, 7, 5, 9, 8};
mySort<int> aInt(arrInt, 5);
aInt.sortAlgorithm();
aInt.displayData();
//test with float data
float arrFloat[5] = {25.5, 32.3, 15.0, 11.2, 9.0};
mySort<float> afloat(arrFloat, 5);
afloat.sortAlgorithm();
afloat.displayData();
//test with integer data
char arrChar[5] = {'z', 'v', 'a', 'r', 'm'};
mySort<char> aChar(arrChar, 5);
aChar.sortAlgorithm();
aChar.displayData();
return 0;
}
=======screen shot of the code=========
Output: