Line | |
---|
1 | /* |
---|
2 | * swift_context.c |
---|
3 | * |
---|
4 | * (c) 2009 Ionut Rosoiu <ionut.rosoiu@gmail.com> |
---|
5 | * |
---|
6 | */ |
---|
7 | |
---|
8 | #include <stdio.h> |
---|
9 | #include <stdlib.h> |
---|
10 | #include "swift_compiler.h" |
---|
11 | |
---|
12 | extern void read_array(char *filename, int **arr, int *n); |
---|
13 | extern void free_array(int *arr); |
---|
14 | extern void print_array(int *arr, int n); |
---|
15 | extern void check_array(int *arr, int n); |
---|
16 | |
---|
17 | void swap(int *a, int *b) |
---|
18 | { |
---|
19 | int tmp = *a; |
---|
20 | *a = *b; |
---|
21 | *b = tmp; |
---|
22 | } |
---|
23 | |
---|
24 | int partition(int *a, int l, int r) |
---|
25 | { |
---|
26 | int pivot = a[l]; |
---|
27 | int i = l; |
---|
28 | int j = r + 1; |
---|
29 | |
---|
30 | while (1) { |
---|
31 | do { |
---|
32 | ++i; |
---|
33 | } while (a[i] <= pivot && i <= r); |
---|
34 | |
---|
35 | do { |
---|
36 | --j; |
---|
37 | } while (a[j] > pivot); |
---|
38 | |
---|
39 | if (i >= j) { |
---|
40 | break; |
---|
41 | } |
---|
42 | |
---|
43 | swap(&a[i], &a[j]); |
---|
44 | } |
---|
45 | |
---|
46 | swap(&a[l], &a[j]); |
---|
47 | return j; |
---|
48 | } |
---|
49 | |
---|
50 | void qs(int *a, int l, int r) |
---|
51 | { |
---|
52 | int pivot; |
---|
53 | |
---|
54 | if (l < r) { |
---|
55 | pivot = partition(a, l, r); |
---|
56 | qs(a, l, pivot-1); |
---|
57 | qs(a, pivot+1, r); |
---|
58 | } |
---|
59 | } |
---|
60 | |
---|
61 | int quicksort(int *a, int size) |
---|
62 | { |
---|
63 | qs(a, 0, size - 1); |
---|
64 | return 0; |
---|
65 | } |
---|
66 | |
---|
67 | int main(int argc, char **argv) |
---|
68 | { |
---|
69 | int n, r, *a; |
---|
70 | |
---|
71 | if (argc != 2) { |
---|
72 | fprintf(stderr, "usage: %s <input_file>\n", argv[0]); |
---|
73 | abort(); |
---|
74 | } |
---|
75 | |
---|
76 | read_array(argv[1], &a, &n); |
---|
77 | print_array(a, n); |
---|
78 | |
---|
79 | r = quicksort(a, n); |
---|
80 | |
---|
81 | check_array(a, n); |
---|
82 | |
---|
83 | free_array(a); |
---|
84 | |
---|
85 | printf("done.\n"); |
---|
86 | return 0; |
---|
87 | } |
---|
Note: See
TracBrowser
for help on using the repository browser.