Selection Sort in Array
Selection Sort is a sorting algorithm that selects the smallest element from an unsorted list in each iteration and places.That element at the beginning of the unsorted list.In this sort we have to compare 1st element with all the index elements
Working procedure
Lets take an array
example 64 25 12 22 11
first pass:
64 25 12 22 11
---> 11 25 12 22 64
second pass:
11 25 12 22 64
11 is already sorted so next we have compare 12 to all the elements
11 12 25 22 64
Third pass:
11 12 25 22 64
11 12 25 22 64
Forth pass:
11 12 22 25 64
Selection sort algorithm :
selectionSort(array,size)
repeat(size-1)times
set the first unsorted element as the minimum
for each of the unsorted elements
if element<current Minimum
set element as new minimum
swap minimum with 1st unsorted position
Pseudocode:
list:array of items
n:size of list
for i=1 to n-1
min=i
for j=i+1 to n
if list[j]<list[min] then
min=j;
end if
end for
if indexMin!=i then
swap list[Min] and list[i]
end if
end for
end procedure
Implementation:
#include <stdio.h>
#include <stdlib.h>
void selection(int array[], int n)
{
int i, j, minimum;
for (i = 0; i < n-1; i++)
{
minimum = i;
for (j = i+1; j < n; j++)
if (array[j] < array[minimum])
minimum = j;
int temp = array[minimum];
array[minimum] = array[i];
array[i] = temp;
}
}
void printArr(int array1[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ", array1[i]);
}
int main()
{
int array1[] = { 15, 30, 29, 14, 39, 11 };
int n = sizeof(array1) / sizeof(array1[0]);
printf(" An array before sorting: - \n");
printArr(array1, n);
selection(array1, n);
printf("\nAn Array after sorting- \n");
printArr(array1, n);
return 0;
}
output:
An array before sorting: -
15 30 29 14 39 11
An Array after sorting-
11 14 15 29 30 39
Process returned 0 (0x0) execution time : 0.081 s
Press any key to continue.
0 Comments