Debian Codegraph @

test/sortu.awk

raw
1 # numeric before string, ascending by index
2 function comp_num_str(s1, v1, s2, v2, n1, n2) {
3 n1 = s1 + 0
4 n2 = s2 + 0
5 if (n1 == s1)
6 return (n2 == s2) ? (n1 - n2) : -1
7 else if (n2 == s2)
8 return 1
9 return (s1 < s2) ? -1 : (s1 != s2)
10 }
11
12 # ascending index number
13 function comp_idx_num(s1, v1, s2, v2)
14 {
15 return (s1 - s2)
16 }
17
18 # ascending value number
19 function comp_val_num(s1, v1, s2, v2, num)
20 {
21 num = "^[-+]?([0-9]+[.]?[0-9]*|[.][0-9]+)([eE][-+]?[0-9]+)?$"
22 # force stable sort, compare as strings if not numeric
23 if ((v1 - v2) == 0 && (v1 !~ num || v2 !~ num))
24 return comp_val_str(s1, v1, s2, v2)
25 return (v1 - v2)
26 }
27
28 # ascending value string
29 function comp_val_str(s1, v1, s2, v2)
30 {
31 v1 = v1 ""
32 v2 = v2 ""
33 return (v1 < v2) ? -1 : (v1 != v2)
34 }
35
36 # deterministic, by value (and index), descending numeric
37 function comp_val_idx(s1, v1, s2, v2)
38 {
39 return (v1 != v2) ? (v2 - v1) : (s2 - s1)
40 }
41
42 BEGIN {
43 a[1] = 10; a[100] = 1; a[2] = 200
44 a["cat"] = "tac"; a["rat"] = "tar";a["bat"] = "tab"
45
46 print "--- number before string, ascending by index ---"
47 PROCINFO["sorted_in"] = "comp_num_str"
48 for (i in a)
49 printf("%-10s%-s\n", i, a[i])
50
51 delete a
52 a[11] = 10; a[100] = 5; a[2] = 200
53 a[4] = 1; a[20] = 10; a[14] = 10
54 print "--- deterministic, by value (index), descending numeric ---"
55 PROCINFO["sorted_in"] = "comp_val_idx"
56 for (i in a)
57 printf("%-10s%-s\n", i, a[i])
58
59 for (IGNORECASE=0; IGNORECASE <= 1; IGNORECASE++) {
60 makea(a)
61 SORT_STR = "comp_val_num"
62 printf("--- asort(a, b, \"%s\"), IGNORECASE = %d---\n", SORT_STR, IGNORECASE)
63 asort2(a, "")
64
65 makea(a)
66 SORT_STR = "comp_val_str"
67 printf("--- asort(a, b, \"%s\"), IGNORECASE = %d---\n", SORT_STR, IGNORECASE)
68 asort2(a, "")
69
70 makea(a)
71 SORT_STR = "comp_val_str"
72 printf("--- asort(a, a, \"%s\"), IGNORECASE = %d---\n", SORT_STR, IGNORECASE)
73 asort1(a, "")
74 }
75 }
76
77 function makea(aa)
78 {
79 delete aa
80 aa[1] = "barz";
81 aa[2] = "blattt";
82 aa[3] = "Zebra";
83 aa[4] = 1234;
84 aa[5] = 234;
85 }
86
87 # source array != destination array
88 function asort2(c, s, d, k, m)
89 {
90 if (SORT_STR < 0)
91 m = asort(c, d);
92 else
93 m = asort(c, d, SORT_STR);
94 for (k=1; k <= m; k++) {
95 if (isarray(d[k]))
96 asort2(d[k], s"["k"]")
97 else
98 printf("%-10s:%-10s%-10s\n", s"["k"]", c[k], d[k])
99 }
100 }
101
102 # source array == destination array
103 function asort1(c, s, k, m)
104 {
105 if (SORT_STR < 0)
106 m = asort(c)
107 else if (SORT_STR != "")
108 m = asort(c, c, SORT_STR)
109 else
110 m = asort(c, c);
111
112 for (k=1; k <= m; k++) {
113 if (isarray(c[k]))
114 asort1(c[k], s"["k"]")
115 else
116 printf("%-10s:%-10s\n", s"["k"]", c[k])
117 }
118 }