forked from Privanom/algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
selection_sort.c
92 lines (78 loc) · 1.33 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
#include <stdio.h>
#include <stdlib.h>
void print_arr(int *ptr, int size)
{
putchar('[');
while(size--)
{
printf("%d", *ptr++);
if(size)
putchar(',');
}
printf("]\n");
}
void swap(int *a, int *b)
{
int tmp;
tmp = *a;
*a = *b;
*b = tmp;
}
int *find_min(int *ptr, int size)
{
int *min;
min = ptr;
while(size--)
{
if(*ptr < *min)
min = ptr;
ptr++;
}
return (min);
}
void selection_sort(int *ptr, int size)
{
int *min;
while(--size)
{
if((min = find_min(ptr + 1, size)))
{
if(*ptr > *min)
swap(ptr, min);
}
ptr++;
}
}
void fill(char **av, int *ptr, int size)
{
int i;
i = 2;
while(av[i] && size--)
*ptr++ = atoi(av[i++]);
}
int main(int argc, char *argv[])
{
if(argc < 3)
{
puts("Usage: ./your-executable-name [array size] [array]");
puts("Example: ./your-executable-name 3 2 1 0");
return EXIT_FAILURE;
}
int size = atoi(argv[1]);
if(!size)
{
puts("Error: size of array can't be 0");
return EXIT_FAILURE;
}
int *arr = (int *)malloc(size * sizeof(int));
if(!arr)
return EXIT_FAILURE;
fill(argv, arr, size);
printf("Before sorting: ");
print_arr(arr, size);
selection_sort(arr, size);
printf("After sorting: ");
print_arr(arr, size);
free(arr);
return EXIT_SUCCESS;
}