-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathselection-sort.c
56 lines (46 loc) · 1.17 KB
/
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
#include <stdio.h>
void swap(int *x, int *y){
int temp = *x;
*x = *y;
*y = temp;
}
void print_array(int arr[], int size){
for(int i=0; i<size; i++){
printf("%d ", arr[i]);
}
printf("\n---------------\n");
}
int find_smallest(int arr[], int elements){
int smallest = arr[0];
int smallest_index = 0;
for (int i=0; i < elements; i++){
if (arr[i] < smallest){
smallest = arr[i];
smallest_index = i;
}
}
return smallest_index;
}
void selection_sort(int arr[], int elements){
int smallest;
for (int i=0; i < elements - 1; i++){
smallest = i;
for (int j=i+1; j < elements; j++){
if (arr[j] < arr[smallest])
smallest = j;
}
swap(&arr[smallest], &arr[i]);
}
}
void main(){
int array[] = {11,13,25,7,8,3,4,15,6,20};
int elements = 10;
int smallest;
smallest = find_smallest(array, elements);
printf("The smallest index is %d\n", smallest);
printf("Un-Sorted array\n");
print_array(array, elements);
selection_sort(array, elements);
printf("Sorted array\n");
print_array(array, elements);
}