C program to sort an array using Selection Sort technique.

Posted by Mangesh on March 16, 2018

Description :

Selection sort is a sorting algorithm using with we can sort the array in increasing or decreasing order.

Logic :

Selection sort is a sorting technique where we find the smallest number in an array and exchange it with first element. And then we find second smallest element in the array and exchange it with second location element. We continue this process till n-1 times. After n-1 pass we get the sort array.

The time complexity of Selection sort is O(n2).
And it requires n-1 number of swaps.

Program :

#include<stdio.h>
#include<conio.h>
void SelectionSort(int arr[],int n)
{
int i,j,smallest,temp=0;
  for(i=0; i<n-1; i++)
  {
    smallest = i;
    for(j=i+1; j<n; j++)
    {
       if(arr[smallest] > arr[j])
	     smallest = j;
    }
    temp = arr[i];
    arr[i] = arr[smallest];
    arr[smallest] = temp;
  }
}
void printarray(int arr[],int n)
{
int i;
    for(i=0; i<n; i++)
      printf("%d ",arr[i]);
}
void main()
{
int arr[10];
int i,n;
clrscr();
    printf("Enter the total number of element: ");
    scanf("%d",&n);
    for(i=0;i<n;i++)
    {
      printf("Enter %d number in array: ",i+1);
      scanf("%d",&arr[i]);
    }
    printf("\n_________Before Selection Sort__________\n\n");
    printarray(arr,n);
    SelectionSort(arr,n);
    printf("\n\n_________After Selection Sort__________\n\n");
    printarray(arr,n);
getch();
}

Output :

C program for selection sort` tested in Turbo C 3.2

Written with from Mangesh.

Related Post
1 C program sort array using Bubble Sort technique.
2 C program for sorting an array using Insertion Sort technique.
3 C program to sort an array using Selection Sort technique.
Latest Post
1 C program to implement Queue using linked list.
2 C program for binary search tree (BST).
3 C program to search an element in linked list.
4 C program for postorder traversal in binary tree.
5 C program for preorder traversal in binary tree.