Selection Sort Algorithm

 Selection Sort algorithm is used to arrange a list of elements in a particular order (Ascending or Descending). In selection sort, the first element in the list is selected and it is compared repeatedly with all the remaining elements in the list. If any element is smaller than the selected element (for Ascending order), then both are swapped so that first position is filled with the smallest element in the sorted order. Next, we select the element at a second position in the list and it is compared with all the remaining elements in the list. If any element is smaller than the selected element, then both are swapped. This procedure is repeated until the entire list is sorted.
 
Step by Step Process

The selection sort algorithm is performed using the following steps...

  • Step 1 - Select the first element of the list (i.e., Element at first position in the list).
  • Step 2: Compare the selected element with all the other elements in the list.
  • Step 3: In every comparison, if any element is found smaller than the selected element (for Ascending order), then both are swapped.
  • Step 4: Repeat the same procedure with element in the next position in the list till the entire list is sorted.
  Selection Sort Logic 
 
for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(a[position] > a[j])
position=j;
}
if(position != i)
{
swap=a[i];
a[i]=a[position];
a[position]=swap;
}
}
 
Example 
 

 
Implementation of Selection Sort Algorithm using C Programming Language
 
#include <stdio.h>
int main()
{
int arr[100], n, i, j, position, swap;
printf("Enter the number of elements to be sorted: ");
scanf("%d", &n);
for (i = 0; i < n; i++)
{
    printf("Enter element no. %d: ", i+1);
    scanf("%d", &arr[i]);
}

for(i = 0; i < n - 1; i++)
{
position=i;
for(j = i + 1; j < n; j++)
{
if(arr[position] > arr[j])
position=j;
}
if(position != i)
{
swap=arr[i];
arr[i]=arr[position];
arr[position]=swap;
}
}
printf("Sorted Array:\n");
for(i = 0; i < n; i++)
printf("%d ", arr[i]);
return 0;
 
Output 


No comments:

Post a Comment