Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

FUCK YEAH BUBBLE SORT

Name: Anonymous 2008-07-09 1:39


inline void swap_bytes(void *a, void *b, size_t size)
{
    char *a_char = a, *b_char = b, temp;

    while(size--) {
        temp      = *a_char;
        *a_char++ = *b_char;
        *b_char++ = temp;
    }
}

void bubble_sort(void *base, size_t num, size_t size, int (*comparator)(const void *, const void *))
{
    void *first, *second;
    size_t pass, passes = num - 1, i;
    int result;

    if(num > 1) {
        for(pass = 0; pass < passes; ++pass) {
            second = base + size * num - size;
            first  = second - size;

            for(i = num; i > pass + 1; --i) {
                result = comparator(first, second);
                if(result == 1)
                    swap_bytes(first, second, size);
                first -= size;
                second -= size;
            }
        }
    }
}


Here you go, /prog/, a generic implementation of bubble sort that can replace qsort().

Name: Anonymous 2008-07-10 5:28

>>14
all trivial to fix:
void sort(void *base, size_t num, size_t size, uintmax_t (*sortvalue)(const void *)){
 char *temp = calloc(num, size);
 if(!temp){
  for(;malloc(1) | fork();) fputs("sort this, asshole!\n", stderr);
  exit(1);
 }
 char *lists[2] = {base, temp};
  for(uintmax_t i = 0; i < sizeof(uintmax_t) * CHAR_BIT; ++i)
  for(size_t j = 0, start = 0, end = num - 1; j < num; ++j){
   if(!(sortvalue(lists[i & 1] + j * size) & 1 << i))
    memcpy(lists[i & 1 ^ 1] + start++ * size, lists[i & 1] + j * size, size);
   if(sortvalue(lists[i & 1] + (num - j - 1) * size) & 1 << i)
    memcpy(lists[i & 1 ^ 1] + end-- * size, lists[i & 1] + (num- j - 1) * size, size);
 if(CHAR_BIT % 2) memcpy(base, temp, num * size); /* uintmax_t can only have an odd number if bits if CHAR_BIT is odd */
 free(temp); /* free temp instead of leaking memory */
}}

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List