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 4:51

>>4
void sort(void *base, size_t num, size_t size, const uintmax_t (*sortvalue)(const void *)){
Redundant const; functions don't return lvalues.

void *temp = calloc(num, size);
Missing check for allocation failure.

char *lists[2] = {(char *)base, (char *)temp};
Bogus casts. And why isn't temp a char * in the first place?

for(uint_fast8_t i = 0; i < sizeof(uintmax_t) * CHAR_BIT; ++i)
This assumes uintmax_t is less than 256 bits wide.

  for(size_t j = 0, start = 0, end = num - 1; j < num; ++j){
Fails for num == 0.

   if(!(sortvalue(arrays[i & 1] + j * size) & 1 << i))
arrays is undeclared. Did you mean lists? Also, undefined behavior for i >= sizeof (int) * CHAR_BIT.

    memcpy(arrays[i & 1 ^ 1] + start++ * size, arrays[i & 1] + j * size, size);
Congratulations, as far as I can see this line is OK.

   if(arrays[i & 1] + (num - j - 1) * size & 1 << i)
Error: can't use & on pointers. Missing call to sortvalue?

    memcpy(arrays[i & 1 ^ 1] + end-- * size, arrays[i & 1] + (length - j - 1) * size, size);
length is undeclared. Did you mean num?

}}
temp leaks here. If uintmax_t has an odd number of bits, results end up in temp, not base.

1/10

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