diff options
author | Nguyễn Gia Phong <vn.mcsinyx@gmail.com> | 2019-12-28 21:16:58 +0700 |
---|---|---|
committer | Nguyễn Gia Phong <vn.mcsinyx@gmail.com> | 2019-12-28 21:21:44 +0700 |
commit | 0887d8f96950a060a122e14ed2981182ff1eb37d (patch) | |
tree | 68be7a59c323c1fd901455ffae8f21874c4bb4c6 /usth/ICT2.1/labwork/5/Ex1.c | |
parent | e461df7573c2b7b7e26c965d8cf2d8e175d67378 (diff) | |
download | cp-0887d8f96950a060a122e14ed2981182ff1eb37d.tar.gz |
[usth/ICT2.1] Algorithm and Data Structures
Diffstat (limited to 'usth/ICT2.1/labwork/5/Ex1.c')
-rw-r--r-- | usth/ICT2.1/labwork/5/Ex1.c | 58 |
1 files changed, 58 insertions, 0 deletions
diff --git a/usth/ICT2.1/labwork/5/Ex1.c b/usth/ICT2.1/labwork/5/Ex1.c new file mode 100644 index 0000000..e64c6ea --- /dev/null +++ b/usth/ICT2.1/labwork/5/Ex1.c @@ -0,0 +1,58 @@ +/* + * Cocktail shaker sorting integers from stdin + * Copyright (C) 2019, Nguyễn Gia Phong + * This software is licenced under a CC BY-SA 4.0 license + */ + +#include <stdio.h> + +void strswap(char *this, char *that, size_t n) +{ + while (n--) { + this[n] ^= that[n]; + that[n] ^= this[n]; + this[n] ^= that[n]; + } +} + +void csort(void *base, size_t nmemb, size_t size, + int (*compar)(const void *, const void *)) +{ + char *i, *low = base; + char *high = low + nmemb * size; + do { + char *h = i = low; + while ((i += size) < high) + if (compar(i - size, i) > 0) + strswap(i - size, h = i, size); + high = h; + if (low + size >= high) + break; + char *l = i = high; + while ((i -= size) > low) + if (compar(i - size, i) > 0) + strswap(i - size, l = i, size); + low = l; + } while (low + size < high); +} + +int cmp(const void *x, const void *y) +{ + return *(int *) x - *(int *) y; +} + +int main() +{ + size_t n; + scanf("%zu", &n); + int a[n]; + for (int i = 0; i < n; i++) + scanf("%d", a + i); + + csort(a, n, sizeof(int), cmp); + for (int i = 0; i < n; i++) + printf("%d ", a[i]); + putchar(10); + + return 0; +} |