Selection sort
Basic Concept
The time complexity of selection sort is O(n2), for best, average, and worst case scenarios.
Selection sort is one of the basic algorithms for sorting data, its simplicity proves useful for sorting small amounts of data. Selection sort works by first starting at the beginning array (index 0) and traverses the entire array comparing each value with the current index, if it is smaller than the current index than that index is saved. Once the loop has traversed all the data and if a smaller value than the current index was found a swap is made between the current index in the index where the smaller value was found. The current index is then incremented, now to index 1, the algorithm repeats.
PROGRAM
#include<iostream>
using namespace std;
template <class T> // The template class is used to have flexibility in the type of data, whether integer, float, or character it will work for all
void s_sort(T a[],int n)
{
int i,j,t;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i]) //for descending order use if(a[j]>a[i])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}
int main()
{
int a[100],i,n;
cout<<"Enter The number of Element:";
cin>>n;
cout<<"\nEnter Elements\n";
for(i=0;i<n;i++)
{
cout<<"\nEnter:";
cin>>a[i];
}
s_sort(a,n);
cout<<"\nAfter Sorting\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
getch();
return 0;
}
OUTPUT (screenshot):
Basic Concept
The time complexity of selection sort is O(n2), for best, average, and worst case scenarios.
Selection sort is one of the basic algorithms for sorting data, its simplicity proves useful for sorting small amounts of data. Selection sort works by first starting at the beginning array (index 0) and traverses the entire array comparing each value with the current index, if it is smaller than the current index than that index is saved. Once the loop has traversed all the data and if a smaller value than the current index was found a swap is made between the current index in the index where the smaller value was found. The current index is then incremented, now to index 1, the algorithm repeats.
PROGRAM
#include<iostream>
using namespace std;
template <class T> // The template class is used to have flexibility in the type of data, whether integer, float, or character it will work for all
void s_sort(T a[],int n)
{
int i,j,t;
for(i=0;i<n;i++)
{
for(j=i+1;j<n;j++)
{
if(a[j]<a[i]) //for descending order use if(a[j]>a[i])
{
t=a[i];
a[i]=a[j];
a[j]=t;
}
}
}
}
int main()
{
int a[100],i,n;
cout<<"Enter The number of Element:";
cin>>n;
cout<<"\nEnter Elements\n";
for(i=0;i<n;i++)
{
cout<<"\nEnter:";
cin>>a[i];
}
s_sort(a,n);
cout<<"\nAfter Sorting\n";
for(i=0;i<n;i++)
{
cout<<a[i]<<"\t";
}
getch();
return 0;
}
Comments
Post a Comment