Selection Sort Algorithm || Lesson 2 || Data Structures || Learning Monkey ||

preview_player
Показать описание
Selection Sort Algorithm

In this class, we will try to understand Selection Sort Algorithm.

We have already discussed the Selection Sort Working Mechanism in our previous class.
Selection Sort Algorithm

The Selection Sort Algorithm is shown below.

We will try to understand the working of the selection sort algorithm by using the array as shown below.

The outer for loop of the algorithm will iterate from 0 to 3.

The second line of code min = “i” states the index of the minimum element.

Assuming that the minimum element is at the ith index, the inner for loop will start its iteration.

The inner for loop will now iterate from i + 1 to n.

In every iteration, the element at the A[j] A[min] comparision is done.

If A[j] A[min] is true then the index of min = j.

After completing all iterations, the index of the min element is identified.

Now, the elements A[i] and A[j] get swapped.

After completion of all the iterations, the elements will be in sorted order.
code: less than and greater than symbols changed to lt and gt
#includestdio.h
#includestdlib.h
selection(int a[], int n)
{
int i,j,min,temp;
for(i=0;i lt n-1;i++)
{
min=i;
for(j=i+1;j lt n;j++)
{
if(a[j] lt a[min])
{
min=j;
}
}
temp=a[min];
a[min]=a[i];
a[i]=temp;
}
}
int main()
{
int a[20],n,i;
printf("enetr the value of n");
scanf("%d",&n);
printf("eneter n elements");
for(i=0;i lt n;i++)
{
scanf("%d",&a[i]);
}
selection(a,n);
printf("elements after sorted are");
for(i=0;i lt n;i++)
{
printf("%d",a[i]);
}
return 1;

#datastrctures #gatecse #learningmonkey #placementtraining #gatedatastructures

Link for playlists:

Рекомендации по теме