Selection Sort Algorithm: First it finds the smallest element in the

advertisement
Selection Sort Algorithm:




First it finds the smallest element in the array.
Exchange that smallest element with the element at the first position.
Then find the second smallest element and exchange that element with the element at the
second position.
This process continues until the complete array is sorted.
Selection Sort Pseudo code:
SELECTION-SORT(a)
1. For i := 1 to n
2.
j :=i
3.
For k := j + 1 to n
4.
If a[ k] < a[ k ]
5.
j := k
6.
Exchange a[ i ] ↔ a[ j ]
C++ code:
#include<iostream.h>
int main()
{
int a[20],n,i,j,k,t;
cout<<"n="; cin>>n;
cout<<"input array of data:";
for(i=1;i<=n;i++)
cin>>a[i];
for(i=1;i<=n;i++)
{
j=i;
for(k=i+1;k<=n;k++)
{ if(a[k]<a[j])
{j=k;}
}
t=a[i];a[i]=a[j];a[j]=t;
}
cout<<"sorted output of data:";
for(i=1;i<=n;i++)
cout<<a[i]<<" ";
return 0;
}
Debugging:
Let,
n=5
Input array of data: 8 4 6 5 2
8
4
6
5
2
5
2
Step1:
i=1
Select the 1st data position
8
4
6
At first select the position of smallest data, j=i=1
Find out the location of smallest data, k=i+1=1+1=2 to 5
Now, j=k=5
8
4
6
5
2
Swap the smallest data from 5th position to 1st position data
2
4
6
5
8
5
8
Step2:
i=2
Select the 2nd data position
2
4
6
At first select the position of smallest data, j=i=2
Find out the location of smallest data, k=i+1=2+1=3 to 5
Now, j=2
2
4
6
5
8
Swap the smallest data from 2th position to 2nd position data
2
4
6
5
8
5
8
Step3:
i=3
Select the 3rd data position
2
4
6
At first select the position of smallest data is, j=i=3
Find out the location of smallest data, k=i+1=3+1=4 to 5
Now, j=k=4
2
4
6
5
8
Swap the smallest data from 4th position to 3rd position data
2
4
5
6
8
6
8
Step4:
i=4
Select the 4th data position
2
4
5
At first select the position of smallest data is, j=i=4
Find out the location of smallest data, k=i+1=4+1=5 to 5
Now, j=4
2
4
5
6
8
Swap the smallest data from 4th position to 4th position data
2
4
5
6
8
6
8
Step5:
i=5
Select the 4th data position
2
4
5
At first select the position of smallest data is, j=i=5
k=i+1=5+1=6 to 5 so the inner loop is end.
The location of smallest data, j=5
2
4
5
6
8
Swap the smallest data from 5th position to 5th position data
2
4
5
6
8
Step 6:
i=6 so the outer loop also end
Sorted output of data is:
2
4
5
6
8
Download