Selection sort | Sorting algorithm
The selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
Time Complexity: O(n2) as there are two nested loops.
The algorithm maintains two subarrays in a given array.
1) The subarray which is already sorted.
2) Remaining subarray which is unsorted.
In every iteration of selection sort, the minimum element (considering ascending order) from the unsorted subarray is picked and moved to the sorted subarray.
Source code:
Download the code here: Selection_sort.cpp
#include<iostream>
using namespace std;
//function for performing selection sort
void selection_sort(int a[],int n)
{
int i,j,k,temp,min_indx;
for(i=0;i<n-1;i++)
{
min_indx=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min_indx])
{
min_indx=j;
}
}
// swap
temp=a[min_indx];
a[min_indx]=a[i];
a[i]=temp;
}
}
int main()
{
int a[100],n,k;
cout<<"Enter the no of element: ";
cin>>n;
cout<<"Enter array:\n";
//loop to get user input
for(k=0;k<n;k++)
{
cin>>a[k];
}
selection_sort(a,n);
cout<<"Sorted array\n";
//loop to print sorted arrray
for(k=0;k<n;k++)
{
cout<<a[k]<<" ";
}
return 0;
}
using namespace std;
//function for performing selection sort
void selection_sort(int a[],int n)
{
int i,j,k,temp,min_indx;
for(i=0;i<n-1;i++)
{
min_indx=i;
for(j=i+1;j<n;j++)
{
if(a[j]<a[min_indx])
{
min_indx=j;
}
}
// swap
temp=a[min_indx];
a[min_indx]=a[i];
a[i]=temp;
}
}
int main()
{
int a[100],n,k;
cout<<"Enter the no of element: ";
cin>>n;
cout<<"Enter array:\n";
//loop to get user input
for(k=0;k<n;k++)
{
cin>>a[k];
}
selection_sort(a,n);
cout<<"Sorted array\n";
//loop to print sorted arrray
for(k=0;k<n;k++)
{
cout<<a[k]<<" ";
}
return 0;
}
Output:
Time Complexity: O(n2) as there are two nested loops.
Comments
Post a Comment