In: Computer Science
Code: C++
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
Solutions:
Integer:
In Asc order:
int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+n);
In Desc Order:
int arr[] = {1, 5, 8, 9, 6, 7, 3, 4, 2, 0};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+n, greater<int>());
Doubles
In Asc order:
double arr[] = {1.32, 5.423, 8.234, 9.23, 6.123, 7.324, 3.123,
4.234, 2.235, 0.235};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+n);
In Desc Order:
double arr[] = {1.32, 5.423, 8.234, 9.23, 6.123, 7.324, 3.123,
4.234, 2.235, 0.235};
int n = sizeof(arr)/sizeof(arr[0]);
sort(arr, arr+n, greater<double>());
Student Sort score as Desc Order and name as Asc order;
code:
#include <bits/stdc++.h>
using namespace std;
struct Student
{
string name; // Given
int scores; // Scores
};
// Function for comparing two students according
// to given rules
bool compare(string a, string b) {
if(a.compare(b) < 0)
return true;
else
return false;
}
bool compareTwoStudents(Student a, Student b)
{
// here you can set priority to which parameter you
want to sort first like score and name || name and score
// currently score and name is active ( first score
then name )
if (a.scores != b.scores)
return a.scores > b.scores;
return compare(a.name, b.name);
}
// Fills total marks and ranks of all Students
void computeRanks(Student a[], int n)
{
sort(a, a+5, compareTwoStudents);
}
// Driver code
int main()
{
int n = 5;
// array of structure objects
Student a[n];
// Details of Student 1
a[0].name = "Bryan" ;
a[0].scores = 80 ;
// Details of Student 2
a[1].name= "Kevin" ;
a[1].scores= 95 ;
// Details of Student 3
a[2].name = "Nick" ;
a[2].scores = 95 ;
// Details of Student 4
a[3].name = "AJ" ;
a[3].scores = 80 ;
// Details of Student 5
a[4].name = "Howie" ;
a[4].scores = 80 ;
computeRanks(a, n);
// Display details of Students
for (int i=0; i<n; i++)
{
cout << a[i].name << " " << a[i].scores <<
" "<<endl;
}
return 0;
}
// Happy hack :)
// please let me know if you have any dout.