You need to sort elements of an array where the array can be of following data-types:
- Integer
- String
- floating number
Your task is to complete the given two functions: sortArray() and printArray().
The input line contains 2 lines. The first line contains n(size of array) and q(type of array) separated by space. Below is the description about q.
- q = 1, means elements of the array are of integer type
- q = 2, means elements of the array are of string type
- q = 3, means elements of array are of floating digit type
The second line contains n elements of the array separated by space.
We have to print the elements in sorted form of given type of array separated by space.
Example 1:
Input:
3 3
34.23 -4.35 3.4
Output:
-4.35 3.4 34.23
Explanation:
The array is of floating type. After
sorting the elements of array are as
such: -4.35 3.4 34.23
Example 2:
Input:
4 1
123 -2311 837 0
Output:
-2311 0 123 837
Constraints:
1 <= T <= 50
1 <= n <= 100
1 <= q <= 3
solution<1>:
// { Driver Code Starts
//Initial Template for C++
#include <bits/stdc++.h>
using namespace std;
// } Driver Code Ends
//User function Template for C++
template <class T>
void sortArray(T a[], int n)
{
//Add your code here.
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]>a[j])
{
T temp=a[i];
a[i]=a[j];
a[j]=temp;
}
}
}
}
template <class T>
void printArray(T a[], int n)
{
//Add your code here.
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<"\n";
}
// { Driver Code Starts.
int main()
{
int t;
cin>>t;
while(t--)
{
int n, q, i;
cin>>n>>q;
int intArr[n];
string strArr[n];
float floatArr[n];
switch(q)
{
case 1:
for(i=0; i<n; i++)
{
cin>>intArr[i];
}
sortArray(intArr, n);
printArray(intArr, n);
break;
case 2:
for(i=0; i<n; i++)
{
cin>>strArr[i];
}
sortArray(strArr, n);
printArray(strArr, n);
break;
case 3:
for(i=0; i<n; i++)
{
cin>>floatArr[i];
}
sortArray(floatArr, n);
printArray(floatArr, n);
break;
}
}
return 0;
}
// } Driver Code Ends
solution<2>:
//User function Template for C++
template <class T>
void sortArray(T a[], int n)
{
//Add your code here.
sort(a,a+n);
}
template <class T>
void printArray(T a[], int n)
{
//Add your code here.
for(int i=0;i<n;i++)
{
cout<<a[i]<<" ";
}
cout<<"\n";
}
No comments:
Post a Comment