Line | Count | Source |
1 | | /* |
2 | | * Code adapted from uClibc-0.9.30.3 |
3 | | * |
4 | | * It is therefore covered by the GNU LESSER GENERAL PUBLIC LICENSE |
5 | | * Version 2.1, February 1999 |
6 | | * |
7 | | * Wolfgang Denk <wd@denx.de> |
8 | | */ |
9 | | |
10 | | /* This code is derived from a public domain shell sort routine by |
11 | | * Ray Gardner and found in Bob Stout's snippets collection. The |
12 | | * original code is included below in an #if 0/#endif block. |
13 | | * |
14 | | * I modified it to avoid the possibility of overflow in the wgap |
15 | | * calculation, as well as to reduce the generated code size with |
16 | | * bcc and gcc. */ |
17 | | |
18 | | #include <linux/types.h> |
19 | | #include <common.h> |
20 | | #include <qsort.h> |
21 | | |
22 | | void qsort(void *base, |
23 | | size_t nel, |
24 | | size_t width, |
25 | | int (*comp)(const void *, const void *)) |
26 | 698 | { |
27 | 698 | size_t wgap, i, j, k; |
28 | 698 | char tmp; |
29 | | |
30 | 698 | if (nel < 2 || width == 0) |
31 | 306 | return; |
32 | | |
33 | | /* check for overflow */ |
34 | 392 | if (nel > ((size_t)(-1)) / width) |
35 | 0 | return; |
36 | | |
37 | 392 | wgap = 0; |
38 | 921 | do { |
39 | 921 | wgap = 3 * wgap + 1; |
40 | 921 | } while (wgap < (nel - 1) / 3); |
41 | | |
42 | | /* |
43 | | * From the above, we know that either wgap == 1 < nel or |
44 | | * ((wgap-1) / 3 < (int) ((nel - 1) / 3) <= (nel - 1) / 3 ==> wgap < nel. |
45 | | */ |
46 | 392 | wgap *= width; /* So this can not overflow if wnel doesn't. */ |
47 | 392 | nel *= width; /* Convert nel to 'wnel' */ |
48 | 921 | do { |
49 | 921 | i = wgap; |
50 | 1.01M | do { |
51 | 1.01M | j = i; |
52 | 1.41M | do { |
53 | 1.41M | char *a; |
54 | 1.41M | char *b; |
55 | | |
56 | 1.41M | j -= wgap; |
57 | 1.41M | a = j + ((char *)base); |
58 | 1.41M | b = a + wgap; |
59 | | |
60 | 1.41M | if (comp(a, b) <= 0) |
61 | 994k | break; |
62 | | |
63 | 423k | k = width; |
64 | 3.38M | do { |
65 | 3.38M | tmp = *a; |
66 | 3.38M | *a++ = *b; |
67 | 3.38M | *b++ = tmp; |
68 | 3.38M | } while (--k); |
69 | 423k | } while (j >= wgap); |
70 | 1.01M | i += width; |
71 | 1.01M | } while (i < nel); |
72 | 921 | wgap = (wgap - width) / 3; |
73 | 921 | } while (wgap); |
74 | 392 | } |
75 | | |
76 | | int strcmp_compar(const void *p1, const void *p2) |
77 | 0 | { |
78 | 0 | return strcmp((const char *)p1, (const char *)p2); |
79 | 0 | } |