Selection Sort in C
arr[] = 64 25 12 22 11 // Find the minimum element in arr[0...4] // and place it at beginning 11 25 12 22 64 // Find the minimum element in arr[1...4] // and place it at beginning of arr[1...4] 11 12 25 22 64 // Find the minimum element in arr[2...4] // and place it at beginning of arr[2...4] 11 12 22 25 64 // Find the minimum element in arr[3...4] // and place it at beginning of arr[3...4] 11 12 22 25 64
Input:
8
6 -5 17 2 90 12 34 1
Output:
-5 1 2 6 12 17 34 90
Solution:
#include <stdio.h>
void swap (int a, int b)
{
int t;
t = a;
a = b;
b = t;
}
void SelectionSortArray (int *arr, int len)
{
for (int i = 0; i < len; i++)
{
int min = i;
int t = 0;
for (int j = i; j < len; j++)
{
if (arr[j] < arr[min])
{
min = j;
}
}
t = arr[i];
arr[i] = arr[min];
arr[min] = t;
}
}
int main ()
{
int a[100], n;
scanf ("%d", &n);
for (int i = 0; i < n; i++)
{
scanf ("%d", &a[i]);
}
SelectionSortArray (a, n);
for (int i = 0; i < n; i++)
{
printf ("%d\t", a[i]);
}
return 0;
}
_________________________________________________________
Related Articles:
Sorting array in descending order using bubble sort
Please Like, Comment and Share!😉
Comments
Post a Comment