Implementation of selection sort using C in dataStructure developerIndian.com

Updated:13/08/2023 by Computer Hope

Go Back



This article belongds to detail idea on ,how we can implement selection sort in c and usecases

Choosing Sort is a straightforward sorting method that starts the array with the smallest (or maximum, depending on the order) element each time it is chosen from the unsorted section. The algorithm operates as follows:

  • Selection: The array is divided into two parts: sorted and unsorted. Initially, the sorted part is empty, and the unsorted part contains all elements.
  • Find Minimum: Iterate through the unsorted part to find the minimum element.
  • Swap: Swap the minimum element with the first element of the unsorted part.
  • Expand Sorted Part: The first element of the unsorted part is now considered as part of the sorted portion.
  • Repeat: Repeat steps 2-4 until the entire array is sorted.

Selection Sort with example


            //Selection Sorting
#include<stdio.h>
#include<conio.h>
void main()
{
  int x[10],i,j,t,s,p;
  printf("\nEnter 10 number:");
  for(i=0;i<10;i++)
	 scanf("%d",&x[i]);
  printf("\nEntered element before sorting:");
  for(i=0;i<10;i++)
	 printf("   %d",x[i]);
  for(i=0;i<9;i++)
  {
	 for(j=i+1;j<10;j++)
	 {
		if(x[i]>x[j])
		{
		  t= x[i];
		  x[i]=x[j];
		  x[j]=t;
		}
	 }//end of j loop
  }
  printf("\nEntered element after sorting:");
  for(i=0;i<10;i++)
	 printf("  %d",x[i]);
  getch();
}
          
          

Conclusion

In this article ,implementation uses a an array arr and its size n. It iterates through the array and for each iteration, it finds the minimum element in the unsorted part of the array and swaps it with the first element of the unsorted part.