aboutsummaryrefslogtreecommitdiff
path: root/src/shellsort.c
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2022-04-09 09:46:17 +0200
committerThomas Schmucker <ts@its1.de>2022-04-09 09:46:17 +0200
commit38f5e364f73967c01f9ed442fe6646e70cb1dde0 (patch)
tree274817eb2793584b0e3d856de5504a614f2b4e89 /src/shellsort.c
parent2863f4f1d2a6a6a8704454824d6c291d2e0d4b5c (diff)
parent154874afda4a8df885e51c01f7681f04fb0b8e61 (diff)
downloaddata-structures-38f5e364f73967c01f9ed442fe6646e70cb1dde0.tar.gz
data-structures-38f5e364f73967c01f9ed442fe6646e70cb1dde0.tar.bz2
data-structures-38f5e364f73967c01f9ed442fe6646e70cb1dde0.zip
Merge branch 'rework-directory-structure'
Diffstat (limited to 'src/shellsort.c')
-rw-r--r--src/shellsort.c63
1 files changed, 63 insertions, 0 deletions
diff --git a/src/shellsort.c b/src/shellsort.c
new file mode 100644
index 0000000..29e6bf8
--- /dev/null
+++ b/src/shellsort.c
@@ -0,0 +1,63 @@
1#include <stdio.h>
2#include <stdlib.h>
3#include <time.h>
4
5#include "util.h"
6
7typedef int T;
8
9void
10shellsort(T a[], size_t n)
11{
12 //static const size_t gaps[] = { 701, 301, 132, 57, 23, 10, 4, 1 };
13
14 // Wikipedia:
15 //static const size_t gaps[] = { 2147483647, 1131376761, 410151271, 157840433, 58548857, 21521774, 8810089, 3501671, 1355339, 543749, 213331, 84801, 27901, 11969, 4711, 1968, 815, 271, 111, 41, 13, 4, 1 };
16
17 // https://www.cs.princeton.edu/~rs/shell/paperF.pdf
18 static const size_t gaps[] = { 1391376, 463792, 198768, 86961, 33936, 13776, 4592, 1968, 861, 336, 112, 48, 21, 7, 3, 1 };
19
20 for ( size_t k = 0; k < NELEM(gaps); ++k ) {
21 const size_t gap = gaps[k];
22
23 for ( size_t i = gap; i < n; i++ ) {
24 size_t j = i;
25 T temp = a[i];
26
27 for ( ; j >= gap && a[j - gap] > temp; j -= gap )
28 a[j] = a[j - gap];
29
30 a[j] = temp;
31 }
32 }
33}
34
35static void
36test(T a[], size_t n)
37{
38 for ( size_t i = 1; i < n; ++i ) {
39 if ( a[i - 1] > a[i] ) {
40 ERROR("sortierung passt nicht");
41 }
42 }
43}
44
45int
46main(void)
47{
48 T a[1000000];
49
50 srand(time(NULL));
51 for ( size_t i = 0; i != NELEM(a); ++i )
52 a[i] = rand() % 1000;
53
54 clock_t start = clock();
55 shellsort(a, NELEM(a));
56 clock_t end = clock();
57
58 test(a, NELEM(a));
59
60 printf("duration: %.3f sec\n", ((double) (end - start)) / CLOCKS_PER_SEC);
61
62 return EXIT_SUCCESS;
63}