Selection Sort in C & C++ – Program & Algorithm

In this instructional exercise, I will clarify about calculation for selection sort in C and C++ utilizing program model.

Probably the most straightforward method is a selection sort. As the name proposes,

selection sort is the selection of a component and maintaining it in sorted control. In selection sort,

the methodology is to locate the most modest number in the cluster and trade it with the incentive in the first position of the exhibit.

Presently, locate the second littlest component in the rest of cluster and trade it with an incentive in the subsequent position, continue till you have arrived at the finish of exhibit.

Presently every one of the components have been sorted in rising request.

The calculation for Selection Sort in C and C++

Let ARR is an exhibit having N components

Peruse ARR

Rehash stage 3 to 6 for I=0 to N-1

Set MIN=ARR[I] and Set LOC=I

Rehash stage 5 for J=I+1 to N

On the off chance that MIN>ARR[J], at that point

(a) Set MIN=ARR[J]

(b) Set LOC=J

[End of if]

[End of stage 4 loop]

  1. Exchange ARR[I] and ARR[LOC] utilizing transitory variable

[End of stage 2 external

loop]

Exit

Program for Selection Sort in C

#include<stdio.h>
 
int main()
{
    int i,j,n,loc,temp,min,a[30];
    printf("Enter the number of elements:");
    scanf("%d",&n);
    printf("\nEnter the elements\n");
 
    for(i=0;i<n;i++)
    {
        scanf("%d",&a[i]);
    }
 
    for(i=0;i<n-1;i++)
    {
        min=a[i];
        loc=i;
        for(j=i+1;j<n;j++)
        {
            if(min>a[j])
            {
                min=a[j];
                loc=j;
            }
        }
 
        temp=a[i];
        a[i]=a[loc];
        a[loc]=temp;
    }
 
    printf("\nSorted list is as follows\n");
    for(i=0;i<n;i++)
    {
        printf("%d ",a[i]);
    }
 
    return 0;
}

Program for Selection Sort in C++

#include<iostream>
 
using namespace std;
 
int main()
{
    int i,j,n,loc,temp,min,a[30];
    cout<<"Enter the number of elements:";
    cin>>n;
    cout<<"\nEnter the elements\n";
 
    for(i=0;i<n;i++)
    {
        cin>>a[i];
    }
 
    for(i=0;i<n-1;i++)
    {
        min=a[i];
        loc=i;
        for(j=i+1;j<n;j++)
        {
            if(min>a[j])
            {
                min=a[j];
                loc=j;
            }
        }
 
        temp=a[i];
        a[i]=a[loc];
        a[loc]=temp;
    }
 
    cout<<"\nSorted list is as follows\n";
    for(i=0;i<n;i++)
    {
        cout<<a[i]<<" ";
    }
 
    return 0;
}

Output

Multifaceted nature for Selection Sort in C and C++

The time multifaceted nature for selection sort program in C and C++ for both most pessimistic scenario

and the normal case is O (n2) on the grounds that the quantity of correlations for the two cases is same.

Leave a Comment

error: Alert: Content is protected!!