Selection Sort | Selection Sort C++ | Selection Sort Algorithm

Selection Sort

In selection sort, the smallest element is selected from the unsorted array list and swapped with the element at the beginning of the unsorted list.

Selection Sort Algorithm

1. Assume the first element in the array as minimum
2. now compare the minimum element with every other element in the list
3. if any other element is smaller than the first element then replace that first element with smaller element.
4. for each iteration, indexing begins from the unsorted element.
5. after each iteration, a smaller element is replaced in front of the unsorted array list.

For Example:

selection sort algorithm

Consider the above example of the selection sort, initially, the first element assumed to be minimum element ie 8.
Now 8 is compared with 5,4,3 and 2 and since 2 is a minimum element in the list therefore 8 is replaced with element 2.
After one iteration, indexing starts from the second element and compares it with the remaining unsorted element in the list. Now element 5 will be compared with 4,3,8 and replace with 3 as a minimum element. Element 4 will be compared with 5,8 and since 4 is already the smaller element compared to 5 and 8, no need to replace the element. this loop continues till the last element.
and finally, the sorted elements are 2,3,4,5,8.


Selection sort algorithm

for(i=0;i<n-1;i++)
int min=i;
 for(j=i+1;j<n.j++)
  { if((a[j]<a[min])
      { min=j;}
   }
     if(min!=i)
   {  swap(a[i]),a[min]);}
  }


Selection Sort C++

#include<iostream>
using namespace std;
 template<typename T>
void  ssort(T a[],int n)
{
for(int x=0; x<n; x++)
{
 int pos = x;
for(int y=x; y<n; y++)
{
if(a[pos]>a[y])
{
pos = y;
}}
int temp = a[x];
a[x] = a[pos];
a[pos] = temp;
}}
 int main()
{
int a[50],n;
cout<<“Enter the number of elements: “;
cin>>n;
cout<<“Enter the elements: “;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
ssort(a,n);
cout<<“\nSorted Array is: “;
for(int i=0;i<n;i++)
cout<<a[i]<<” “;
return 0;
}
OUTPUT:
Enter the number of elements: 10
Enter the elements : 5   3   1   7   9   4   8   6   2   10


Sorted Array is : 1   2   3   4   5   6   7   8   9   10

You must be also searching for these programming languages :


tags: selection sort, selection sort c,  selection sort algorithm, selection sort C++, selection sort in c, selection sort in C++.

Post a Comment

Previous Post Next Post