-
Notifications
You must be signed in to change notification settings - Fork 0
/
Selection-Sort.c
42 lines (39 loc) · 923 Bytes
/
Selection-Sort.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
// Selection sort in C
#include <stdio.h>
// function to sort array using Selection sort
void selectionSort( int array[], int n)
{
int i, j, minIndex, temp;
for (i = 0; i < n; i++)
{
minIndex = i;
for (j = i+1; j < n; j++)
{
// To sort in descending order, change > to < in this line.
// Select the minimum element in each loop.
if (array[j] < array[minIndex])
{
minIndex = j;
}
}
// put min at the correct position
temp = array[i];
array[i] = array[minIndex];
array[minIndex] = temp;
}
}
// function to print an array
void printArray(int array[], int n)
{
int i;
for (i = 0; i < n; i++)
printf("%d ",array[i]);
}
// drivers code
int main()
{
int a[] = {5, 3, 9, 2, 8};
int size = 5;
selectionSort(a, size);
printArray(a, size);
}