Selection Sort

In selection sort elements are arranged in two parts - sorted one and unsorted one.

At first, the sorted part is empty and unsorted part contains all the elements. At the every step, the algorithm finds the minimal element from unsorted part and placed at the end of sorted part. In last of process, unsorted part becomes empty and sorted part contains all the elements in sorted order.


Selection Sort Example

These are the selection sorting technique.

selection sort

Search for the element less than first element. A[2] < A[0] so interchange them.

selection sort

Next search for the next element less than second element. A[2] < A[1] so interchange them.

selection sort

Next search for the next element less than third element. A[4] < A[2] so interchange them.

selection sort

Next search for the next element less than fourth element. A[5] < A[4] so interchange them.

selection sort

Next search for the next element less than fifth element. A[5] < A[4] so interchange them.

selection sort
selection sort

Selection Sorting Algorithm

for i <- 1 to n-1 do
	min <- i;
	for j <- i+1 to n do
	if A[j] < A[i] then 
		min <- j
	if min!= i then
		temp <- A[i]
		A[i] <- A[min]
		A[min] <- temp




Selection Sort Program in C

#include <stdio.h>
void selection_sort(int arr[], int count);
void swap(int *a, int *b);
void selection_sort(int arr[], int count)
{
    int i, j;
    for (i = 0 ;  i < count;i++)
    {
        for (j = i ; j < count; j++)
        {
            if (arr[i] > arr[j])
                swap(&arr[i], &arr[j]);
        }
    }
}
/* Swap two variables */
void swap(int *a, int *b)
{
    int temp;
    temp = *a;
    *a = *b;
    *b = temp;
}

int main()
{
    int array[10], i, count;
    printf("Enter the number of elements: ");
    scanf("%d", &count);
    printf("\nEnter %d numbers : ",count);
    printf("\n");
    for (i = 0; i < count; i++)
        scanf("%d", &array[i]);
    selection_sort(array, count);
    printf("\nSelection Sorted List: ");
    for (i = 0; i < count;i++)
        printf(" %d ", array[i]);
    return 0;
}

Output of the above program :

Enter the number of elements: 5

Enter 5 numbers : 
23
90
44
98
12

Selection Sorted List:  12  23  44  90  98 






Read more articles


General Knowledge



Learn Popular Language