Selection Sort using C language (with every step)
What is selection sorting
The selection algorithm sorts an array by repeatedly finding the smallest element (considering increasing or ascending order) from the unsorted part and putting it at the beginning. The algorithm maintains two subarrays in a given group.
1) Subarray that is already sorted.
2) Remaining subarray that is unsorted.
At each iteration of selection, the minimum value (with regard to rising order) is sorted from the unsorted subarray and moved to the sorted subframe.
Code
#include <stdio.h>
void swap(int *xp, int *yp)
{
int temp = *xp;
*xp = *yp;
*yp = temp;
}
void selectionSort(int a[], int n)
{
int i, j, minIndex;
printf("sorting array of length %d...\n",n);
// n-1 changed to n
for (i = 0; i < n; i++)
{
// in selection sort we find the smallest element
// from array and put it aside, then we
// find the next smallest in the remaining array
// again, and go on and go on
// print it out to easily visualize
for (int i=0;i<n;i++) {
printf("%d ",a[i]);
}
printf("\n");
// find the minimum in remaining array
minIndex = i;
// n-1 is changed to n
for (j = i+1; j < n; j++) {
if (a[j] < a[minIndex])
minIndex = j;
}
// swap the found minimum element with the current i element
swap(&a[minIndex], &a[i]);
}
for (int i=0;i<n;i++) {
printf("%d ",a[i]);
}
printf("\n");
}
int main()
{
int a[] = {1,4,5,2,3,6,7,8};
int b[] = {6,12,15,16,18,
4,11,2,5,6,
7,10,12,5,6,
90,4,88,72,32,
};
selectionSort(a, 8);
selectionSort(b, 20);
return 0;
}
Output for this program is
Thanks for being here
Any problem or query or suggestion please comment below.
Comments
Post a Comment