C program for Selection Sort.

selection-sort.c

Here is a C program to sort the array elements in ascending order using Selection Sort technique:

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

#define SIZE 20

void selection_sort(int arr[]);

void main()
{
	int i,j;
	int array_to_sort[SIZE];
	clrscr();

	//Get the elements of Array
	for(i=0; i<SIZE; i++)
	{
		j = i+1;
		printf("\nEnter element %d: ",j);
		scanf("%d", &array_to_sort[i]);
	}

	//Print the unsorted array.
	printf("\n\nUnsorted elements of Array are: ");	
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	//Sort array.
	selection_sort(array_to_sort);

	//Print the sorted array.
	printf("\n\nSorted elements of Array are: ");	
	for(i=0; i<SIZE; i++)
	{
		printf("%d ",array_to_sort[i]);
	}

	getch();
}

//Logic for Selection Sort.
void selection_sort(int arr[])
{
	int i, j, min_value, min_location, temp;

	for(i=0; i<SIZE-1; i++)
	{
		min_value = arr[i];
		min_location = i;

		for(j=i+1; j<SIZE; j++)
		{
			if(min_value > arr[j])
			{
				min_value = arr[j];
				min_location = j;
			}
		}

		if(min_location != i)
		{
			//Swap arr[i] with arr[min_location]
			temp = arr[i];
			arr[i] = arr[min_location];
			arr[min_location] = temp;
		}
	}
}