Initial data commit

This commit is contained in:
Ingy döt Net 2023-07-01 11:58:00 -04:00
parent 72d218235f
commit f23f22d71c
199087 changed files with 3378941 additions and 0 deletions

View file

@ -0,0 +1,39 @@
#include <stdio.h>
// can be any swap function. This swap is optimized for numbers.
void swap(int *x, int *y) {
if(x == y)
return;
*x ^= *y;
*y ^= *x;
*x ^= *y;
}
void cocktailsort(int *a, size_t n) {
while(1) {
// packing two similar loops into one
char flag;
size_t start[2] = {1, n - 1},
end[2] = {n, 0},
inc[2] = {1, -1};
for(int it = 0; it < 2; ++it) {
flag = 1;
for(int i = start[it]; i != end[it]; i += inc[it])
if(a[i - 1] > a[i]) {
swap(a + i - 1, a + i);
flag = 0;
}
if(flag)
return;
}
}
}
int main(void) {
int a[] = { 5, -1, 101, -4, 0, 1, 8, 6, 2, 3 };
size_t n = sizeof(a)/sizeof(a[0]);
cocktailsort(a, n);
for (size_t i = 0; i < n; ++i)
printf("%d ", a[i]);
return 0;
}

View file

@ -0,0 +1 @@
-4 -1 0 1 2 3 5 6 8 101

View file

@ -0,0 +1,64 @@
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
void swap(char* p1, char* p2, size_t size) {
for (; size-- > 0; ++p1, ++p2) {
char tmp = *p1;
*p1 = *p2;
*p2 = tmp;
}
}
void cocktail_sort(void* base, size_t count, size_t size,
int (*cmp)(const void*, const void*)) {
char* begin = base;
char* end = base + size * count;
if (end == begin)
return;
bool swapped = true;
for (end -= size; swapped; ) {
swapped = false;
for (char* p = begin; p < end; p += size) {
char* q = p + size;
if (cmp(p, q) > 0) {
swap(p, q, size);
swapped = true;
}
}
if (!swapped)
break;
swapped = false;
for (char* p = end; p > begin; p -= size) {
char* q = p - size;
if (cmp(q, p) > 0) {
swap(p, q, size);
swapped = true;
}
}
}
}
int string_compare(const void* p1, const void* p2) {
const char* const* s1 = p1;
const char* const* s2 = p2;
return strcmp(*s1, *s2);
}
void print(const char** a, size_t len) {
for (size_t i = 0; i < len; ++i)
printf("%s ", a[i]);
printf("\n");
}
int main() {
const char* a[] = { "one", "two", "three", "four", "five",
"six", "seven", "eight", "nine", "ten" };
const size_t len = sizeof(a)/sizeof(a[0]);
printf("before: ");
print(a, len);
cocktail_sort(a, len, sizeof(char*), string_compare);
printf("after: ");
print(a, len);
return 0;
}