In this instructional exercise, I will clarify about calculation for choice sort in C and C++ utilizing program model.
Perhaps the least difficult strategy is a determination sort. As the name recommends, determination sort is the choice of a component and maintaining it in arranged control.
In choice sort, the technique 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 the exhibit and trade it with an incentive in the subsequent position, continue till you have arrived at the finish of the cluster.
Presently every one of the components has been arranged in rising request.
The calculation for Selection Sort in C and C++
Let ARR is a cluster 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]
Exchange ARR[I] and ARR[LOC] utilizing impermanent 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