Selection Sort implementation in C
Selection sort is one of the simple algorithm which deals with comparison. It finds the minimum element and makes that element to sit in the front. It keeps on the same process for entire elements.
Let us the discuss the process.
Selection sort:
It makes
the array into two parts. One is sorted and other one is unsorted.
- First, the sorted part doesn’t have a value. The unsorted part has the entire elements.
- The process starts now.
- Each iteration, repeat the process.
- The minimum element is searched in the unsorted part.
- Once, it found, swap it with the first element of the unsorted side.
- Continue this until last element.
C implementation:
#include <stdio.h>
int i, j,
min_Index, t;
for (i = 0; i <
n-1; i++) {
min_Index = i;
for (j = i+1;
j < n; j++) {
if (a[j]
< a[min_Index]) {
min_Index = j;
}
}
// Swap the
minimum to first element
t =
a[min_Index];
a[min_Index] =
a[i];
a[i] = t;
}
}
int main() {
int a[10],n,i;
printf("Enter
the number of elements:");
scanf("%d",&n);
printf("Enter
the elements:");
for(i=0;i<n;i++)
{
scanf("%d",&a[i]);
}
selection_Sort(a,
n);
printf("The
Sorted array is: ");
for (i = 0; i <
n; i++) {
printf("%d ", a[i]);
}
return 0;
}
Output:
Enter the number of elements:5
Enter the elements:12 4 56 789 23
The Sorted array is: 4 12 23 56 789
Yes. The selection sort is successful. Hope, you understood
the concept and program. Keep coding!!!
Comments
Post a Comment