The algorithm works by selecting the smallest unsorted item and then swapping it with the item in the next position to be filled. The selection sort works as follows: you look through the entire array for the smallest element, once you find it you swap it (the smallest element) with the first element of the array. Then you look for the smallest element in the remaining array (an array without the first element) and swap it with the second element. Then you look for the smallest element in the remaining array (an array without first and second elements) and swap it with the third element, and so on. Here is an example,
29, 64, 73, 34, 20,
20, 64, 73, 34, 29,
20, 29, 73, 34, 64
20, 29, 34, 73, 64
20, 29, 34, 64, 73
The worst-case runtime complexity is O(n2).
C Program:
#include<stdio.h>
void main()
{
int n, i, j,k, temp;
printf("Enter the size of array\n");
scanf("%d", &n);
int a[n];
printf("Enter %d elements\n", n);
for(i=0; i < n; i++)
scanf("%d", &a[i]);
for(i=0; i<n; i++)
{
for(j=i+1; j<n; j++)
{
if(a[i] > a[j])
{
temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
printf("Sorted Array is:\n");
for(i=0; i<n; i++)
printf("%d\t", a[i]);
}
Output:
Enter the size of array
5
Enter 5 elements
66
44
33
77
11
Sorted Array is:
11 33 44 66 77
No comments:
Post a Comment