-
Notifications
You must be signed in to change notification settings - Fork 2
/
mysort.c
124 lines (100 loc) · 2.36 KB
/
mysort.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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
#include <stdio.h>
#include <stdlib.h>
#include <sys/time.h>
#include <signal.h>
#include <unistd.h>
#define MAXLEN 1024
#define TRUE 1
#define FALSE 0
typedef struct Link {
int data;
struct Link* next;
} Link;
Link* sort(Link*);
int start_alarm(int);
void catch_alarm();
int main(int argc, char* argv[])
{
Link *head = NULL, *x;
char s[MAXLEN];
if (argc != 3) {
printf("Usage: sort <input list> <timeout>\n");
exit(1);
}
/* read input file assuming one integer per line */
FILE* fp = fopen(argv[1], "r");
if (fp == NULL) {
printf("Error: can't open file: %s\n", argv[1]);
exit(1);
}
while (1) {
if (fgets(s, MAXLEN, fp) == NULL)
break;
x = (Link*) malloc(sizeof(Link));
if (x == NULL) {
printf("Error: malloc failed\n");
exit(1);
}
x->data = atoi(s);
x->next = head;
head = x;
}
fclose(fp);
/* setup alarm */
int timeout = atoi(argv[2]);
if (signal(SIGVTALRM, catch_alarm) == SIG_ERR) {
printf("Error: catch_alarm failed\n");
exit(1);
}
if (start_alarm(timeout) == -1) {
printf("Error: start_alarm failed\n");
exit(1);
}
/* sort input list */
head = sort(head);
/* output sorted list */
for (x = head; x != NULL; x = x->next)
printf("%d\n", x->data);
return 0;
}
Link* sort(Link* x) {
Link *p, *t, *y, *z;
int changed = TRUE;
while (changed == TRUE) {
p = NULL;
changed = FALSE;
y = x;
z = y->next;
while (z != NULL) {
if (y->data >= z->data) {
t = z->next;
changed = TRUE;
y->next = t;
z->next = y;
if (p == NULL)
x = z;
else
p->next = z;
p = z;
z = t;
} else {
p = y;
y = z;
z = y->next;
}
}
}
return x;
}
int start_alarm(int timeout) {
struct itimerval old, new;
new.it_interval.tv_usec = 0;
new.it_interval.tv_sec = 0;
new.it_value.tv_usec = 0;
new.it_value.tv_sec = timeout;
return setitimer(ITIMER_VIRTUAL, &new, &old);
}
void catch_alarm() {
printf("Error: timeout\n");
exit(1);
}