In: Computer Science
Write a very general sort method that can sort any type of data arrays/lists. For example, can sort a list of integers in ascending order, a list of integers in descending order, a list of doubles, a list of student objects (with names and scores) in ascending order of names, or in descending order of scores, … You can use any pre-defined sort function or can code your own. Use your favorite language for implementation. If your language doesn’t support these features, implement a revised version (clearly state the revision you made to the problem with a brief discussion of the language’s weakness.) Then test the following cases:
(a) 4, 3, 7, 2, 1, 9 in ascending order
(b) 4.5, 2.0, 9.0, 8.4, 7.2, 6.1, 20.5, 2.1 in descending order
(c) John 40, Casey 45, Ben 47, Zadi 41, Kay 39, Tay 43 in ascending order of names
(d) John 40, Casey 45, Ben 47, Zadi 41, Kay 39, Tay 43 in descending order of scores
Include your program source code and test cases (may copy paste output or show screenshots) as answer to any coding problem.
// CPP program to sort array of any data types.
#include <bits/stdc++.h>
using namespace std;
// Template formed so that sorting of any
// type variable is possible
template <class T>
void sortArray(T a[], int n)
{
// boolean variable to check that
// whether it is sorted or not
bool b = true;
while (b) {
b = false;
for (size_t i=0; i<n-1; i++) {
// swapping the variable
// for sorting order
if (a[i] > a[i + 1]) {
T temp = a[i];
a[i] = a[i + 1];
a[i + 1] = temp;
b = true;
}
}
}
}
// Template formed so that sorting of any
// type variable is possible
template <class T>
void printArray(T a[], int n)
{
for (size_t i = 0; i < n; ++i)
cout << a[i] << " ";
cout << endl;
}
// Driver code
int main()
{
int n = 4;
int intArr[n] = { 2000, 456, -10, 0 };
sortArray(intArr, n);
printArray(intArr, n);
string strArr[n] = { "We do nothing",
"Hi I have something",
"Hello Join something!",
"(Why to do work)" };
sortArray(strArr, n);
printArray(strArr, n);
float floatArr[n] = { 23.4, 11.4, -9.7, 11.17 };
sortArray(floatArr, n);
printArray(floatArr, n);
return 0;