-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsort_array.c
More file actions
98 lines (75 loc) · 1.51 KB
/
Copy pathsort_array.c
File metadata and controls
98 lines (75 loc) · 1.51 KB
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
93
94
95
96
97
98
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int find_min_and_swap(int *a, int len)
{
int j = 0; //location
int m = a[0]; //min value
for(int i=1; i<len; ++i)
{
if(a[i]<m)
{
m = a[i];
j = i;
}
}
//printf("min value:%d\n", m);
//printf("location:%d\n", j);
//swap the value of a[j] with a[0]
// m = a[j];
a[j] = a[0];
a[0] = m;
return 0;
}
int sort_array(int *a, int len)
{
for(int i=0; i<len-1; ++i)
{
find_min_and_swap(a+i, len-i);
}
return 0;
}
int print_array(int *a, int len)
{
for(int i=0; i<len; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
return 0;
}
int main(int argc, char *argv[])
{
if (argc < 2)
{
printf("Please input a comma-separated array and a number!\n");
return 1;
}
int n = strlen(argv[1]);
int comma_count = 0;
for (int i=0; i<n; ++i)
{
if (argv[1][i] == ',')
{
comma_count += 1;
}
}
int length = comma_count + 1;
// allocate memory for the array of integers
int *a = (int *) malloc(length * 4);
// put the first number into a[0]
a[0] = atoi(&argv[1][0]);
int j = 1;
for (int i=0; i<n; ++i)
{
if (argv[1][i] == ',')
{
a[j] = atoi(&argv[1][i+1]);
j += 1;
}
}
print_array(a, length);
sort_array(a, length);
print_array(a, length);
return 0;
}