Friday, January 21, 2011

28.Selection Sort



Selection Sort Program
Selection sort is a simplicity sorting algorithm. It works as its name as it is. Here are basic steps of selection sort algorithm:
1. Find the minimum element in the list
2. Swap it with the element in the first position of the list
3. Repeat the steps above for all remainder elements of the list starting at the second position.

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

#define MAXSIZE 500
void selection(int elements[], int maxsize);
int elements[MAXSIZE],maxsize;
int main()
{
int i;
printf("\nHow many elements you want to sort:" );
scanf("%d",&maxsize);
printf("\nEnter the values one by one: ");
for (i = 0; i < maxsize; i++)
{
printf ("\nEnter element %i :",i);
scanf("%d",&elements[i]);
}
printf("\nArray before sorting:\n");
for (i = 0; i < maxsize; i++)
printf("[%i], ",elements[i]);
printf ("\n");
selection(elements, maxsize);
printf("\nArray after sorting:\n");
for (i = 0; i < maxsize; i++)
printf("[%i], ", elements[i]);
}

void selection(int elements[], int array_size)
{
int i, j, k;
int min, temp;
for (i = 0; i < maxsize-1; i++)
{
min = i;
for (j = i+1; j < maxsize; j++)
{
if (elements[j] < elements[min])
min = j;
}
temp = elements[i];
elements[i] = elements[min];
elements[min] = temp;
}
}

OUTPUT:
How many elements you want to sort:5

Enter the values one by one:
Enter element 0:8
Enter element 1:5
Enter element 2:6
Enter element 3:4
Enter element 4:2

Array before sorting:
[8],[5],[7],[4],[2].

Array after sorting:
[2],[4],[5],[6],[8].


Dont Miss Another Post Connect With Us !

Enter your email address:

0 comments: