Friday, 10 May 2013

SELECTION SORT

Selection sort is a very simple sorting algorithm, with complexity of O(n^2). In this sorting, unlike the Bubble Sort, we don't have to swap the items each time, rather we just store the index of minimum element of remaining array, and swapping is performed just once in one iteration.


The following image clearly describes the working of Selection Sort:-


Source Code :-
/********************************************************************************/

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

int main()
{
int n,*arr,i,j,tmp,min;
printf("ENTER THE NUMBER OF ELEMENTS : \n");
scanf("%d",&n);

arr=(int *)malloc(sizeof(int)*n);

printf("ENTER THE ELEMENTS OF ARRAY : \n");
for(i=0;i<n;i++)
{
scanf("%d",&arr[i]);
}

for(i=0;i<n-1;i++)
{
min=i;
for(j=i+1;j<n;j++)
{
if(arr[min]>arr[j])
min=j;
}

tmp=arr[i];
arr[i]=arr[min];
arr[min]=tmp;
}
printf("THE SORTED ARRAY IS : \n");

for(i=0;i<n;i++)
{
printf("%d\n",arr[i]);
}
getch();
return 1;
}
/******************************************************************************/

Output :-

No comments:

Post a Comment