Problem Statement: Write a function template for selection sort that inputs, sorts and outputs an integer array and a float array.
Note:- Scroll horizontally to see the full line of code.
#include<iostream>
using namespace std;
template <class T>
void selectionSort(T a[], int n){
for(int i=0;i<n;i++){
T min=10000;
int min_index=i;
for(int j=i;j<n;j++){
if(a[j]<min){
min=a[j];
min_index=j;
}
}
T temp=a[i];
a[i]=a[min_index];
a[min_index]=temp;
}
}
int main(){
int n;
cout<<"For Integer Array:"<<endl;
cout<<"Enter the no. of elements: ";
cin>>n;
int arr[n];
cout<<"Enter the elements in the array: ";
for(int i=0;i<n;i++){
cin>>arr[i];
}
selectionSort(arr,n);
cout<<"The sorted array:";
for(int i=0;i<n;i++){
cout<<arr[i]<<" ";
}
cout<<endl;
int m;
cout<<"For Float Array:"<<endl;
cout<<"Enter the no. of elements: ";
cin>>m;
float arr1[m];
cout<<"Enter the elements in the array: ";
for(int i=0;i<m;i++){
cin>>arr1[i];
}
selectionSort(arr1,m);
cout<<"The sorted array:";
for(int i=0;i<m;i++){
cout<<arr1[i]<<" ";
}
}
Comments
Post a Comment