Skip to content

Instantly share code, notes, and snippets.

@maxgoren
Last active June 13, 2023 19:43
Show Gist options
  • Save maxgoren/5b91057d9e8752640973c5b4a5357459 to your computer and use it in GitHub Desktop.
Save maxgoren/5b91057d9e8752640973c5b4a5357459 to your computer and use it in GitHub Desktop.
after claiming his code worked in C but not in C++, here is u/frymimori's code vs shellsort both, in C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void sorterQ(unsigned long a, int * b) {
unsigned long c = a;
unsigned long d = 0;
unsigned long e;
int f;
while (a != 1) {
a--;
if (b[a] > b[a - 1]) {
d = a - 1;
e = d;
f = b[d];
while (d != 0) {
d--;
if (b[d] < f) {
f = b[d];
e = d;
}
}
b[e] = b[a];
b[a] = f;
}
}
while (d == 0) {
a = c;
while (a != 1) {
a--;
if (b[a] > b[a - 1]) {
d = b[a];
b[a] = b[a - 1];
b[a - 1] = d;
d = 1;
}
}
d ^= 1;
}
return;
}
void shellsort(int a[], int n) {
int h;
for (h = 1; h < n/9; h = 3*h+1);
while (h > 0) {
for (int i = h; i < n; i++) {
int j = i; int v = a[i];
while (j >= h && a[j - h] > v) {
a[j] = a[j - h];
j -= h;
}
a[j] = v;
}
h /= 3;
}
}
void checksort(int a[], int n) {
for (int i = 0; i < n - 1; i++) {
if (a[i+1] < a[i]) {
printf("Sort failed.\n");
return;
}
}
printf("Sorted.\n");
}
int main(int argc, char *argv[]) {
int n = atoi(argv[1]);
int *a = malloc(sizeof(int) * n);
int *b = malloc(sizeof(int) * n);
for (int i = 0; i < n; i++) {
int p = rand() % RAND_MAX;
a[i] = p;
b[i] = p;
}
printf("Sorting: %d items.\n", n);
clock_t start, end;
double time;
start = clock();
shellsort(b, n);
end = clock();
time = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("shellsort finished in: %f s\n", time);
checksort(b, n);
start = clock();
sorterQ(n, a);
end = clock();
time = ((double)(end - start)) / CLOCKS_PER_SEC;
printf("Redditer sort finished in: %f s\n", time);
checksort(a, n);
return 0;
}
/*
max@MaxGorenLaptop:/mnt/c/Users/mgoren/langtonsJava$ ./stupider 1000 ; ./stupider 10000 ; ./stupider 100000
Sorting: 1000 items.
shellsort finished in: 0.000085 s
Sorted.
Redditer sort finished in: 0.001011 s
Sort failed.
Sorting: 10000 items.
shellsort finished in: 0.001316 s
Sorted.
Redditer sort finished in: 0.144406 s
Sort failed.
Sorting: 100000 items.
shellsort finished in: 0.033668 s
Sorted.
Redditer sort finished in: 19.408300 s
Sort failed.
max@MaxGorenLaptop:/mnt/c/Users/mgoren/langtonsJava$
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment