C program for Selection Sort Algorithm | C Code champs

C program for Selection Sort Algorithm | C Code champs

270
1
SHARE

C program for Selection Sort Algorithm: Selection sort basically determines the minimum (or maximum) of the list and swaps it with the element at the index where its supposed to be. The process is repeated such that the nth minimum (or maximum) element is swapped with the element at the n-1th index of the list. The below is an implementation of the algorithm in C.

void SelectionSort(int a[], int array_size)
{
     int i;
     for (i = 0; i < array_size - 1; ++i)
     {
          int j, min, temp;
          min = i;
          for (j = i+1; j < array_size; ++j)
          {
               if (a[j] < a[min])
                    min = j;
          }

          temp = a[i];
          a[i] = a[min];
          a[min] = temp;
     }
}

Consider the following table. (Note that each pass represents the status of the array after the completion of the inner for loop, except for pass 0, which represents the array as it was passed to the function for sorting)

8 6 10 3 1 2 5 4 } pass 0
1 6 10 3 8 2 5 4 } pass 1
1 2 10 3 8 6 5 4 } pass 2
1 2 3 10 8 6 5 4 } pass 3
1 2 3 4 8 6 5 10 } pass 4
1 2 3 4 5 6 8 10 } pass 5
1 2 3 4 5 6 8 10 } pass 6
1 2 3 4 5 6 8 10 } pass 7

At pass 0, the list is unordered. Following that is pass 1, in which the minimum element 1 is selected and swapped with the element 8, at the lowest index 0. In pass 2, however, only the sublist is considered, excluding the element 1. So element 2, is swapped with element 6, in the 2nd lowest index position. This process continues till the sub list is narrowed down to just one element at the highest index (which is its right position).

C program for Selection Sort Algorithm :

#include<stdio.h>
#include<conio.h>

int main()
{
int a[100],n,i,j,temp,loc,min;
printf("------------------------------------------------------------------\n");
printf("---------------------- Made by C code champ ----------------------\n");
printf("------------------------------------------------------------------\n\n");
printf("\nEnter the number of elements : ");
scanf("%d",&n);
printf("Enter the element of array : \n");
  for(i=0;i<=n-1;i++)
  {
     scanf("%d",&a[i]);
     }
     min=a[0];
for(i=0;i<=n-1;i++)
   {
    min=a[i];
    loc=i;
    for(j=i+1;j<=n-1;j++)
       {
	if(a[j]<min)
	 {
	  min=a[j];
	  loc=j;
	 }
	 }
if(loc!=1)
   {
     temp=a[i];
     a[i]=a[loc];
     a[loc]=temp;
   }

}
printf("The list of elements after applying selection sort :\n");
for(i=0;i<=n-1;i++)
{
printf("%d\t",a[i]);
}
getch();
}

Let us know in case of any queries regarding program or sorting algorithm.

1 COMMENT

LEAVE A REPLY