functiontemp_5
functiontemp_5
Write a function template for selection sort that inputs, sorts and outputs an
integer array and a float
array.
*/
#include<iostream>
using namespace std;
int n;
#define size 10
template<class T>
void sel(T A[size]) // sel function is called to sort the integer array.
{
int i, j, min;
T temp; /// This declares a temporary variable of type T to
hold values during the swap operation.
for(i = 0; i < n - 1; i++)
{
min = i;
for(j = i + 1; j < n; j++) // searches for the minimum element in the
remaining unsorted part of the array.
{
if(A[j] < A[min])
min = j;
}
temp = A[i];
A[i] = A[min];
A[min] = temp;
}
cout << "\nSorted array:";
for(i = 0; i < n; i++)
{
cout << " " << A[i];
}
}
int main()
{
int A[size];
float B[size];
int i;
/*
Theory
The program demonstrates function templates in C++ to implement selection sort for
sorting integer and float arrays, using the same function for different data types.
Definition
Function Template: A generic function that works with any data type.
Selection Sort: A sorting algorithm that repeatedly selects the smallest element
and places it in its correct position.
Template Class T: A placeholder for data types like integers and floats.
Algorithm
Define a template function sel() to sort any array type.
Input integer and float arrays.
Use selection sort to sort the arrays.
Print the sorted arrays.
Advantages
Reusability: The template allows sorting of both integers and floats using one
function.
Simplicity: Easy to implement and understand.
In-place Sorting: No extra memory needed apart from the array.
Disadvantages
Time Complexity: O(n²), inefficient for large datasets.
No Optimization: Doesn’t improve performance for partially sorted arrays.
Application
Small Data Sets: Used when sorting small datasets or for educational purposes.
Embedded Systems: Suitable for environments with limited memory.
Conclusion
The program demonstrates function templates with selection sort to sort both
integer and float arrays. While simple and useful for small datasets, it’s not
efficient for large data due to its O(n²) time complexity.
*/