Advertisement
aaaaaa123456789

Bubblesort

Apr 14th, 2014
119
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. void bubblesort (void * array, unsigned item_count, unsigned item_size, int (* comparison) (void *, void *)) {
  2.   // This algorithm is for benchmarking only, not for production use. Bubbles are slow at sorting!
  3.   if (!(array && item_size && item_count && comparison)) return; // no point in sorting invalid or empty stuff
  4.   if (item_count == 1) return; // or sorting just one value
  5.   char * buf = malloc(item_size); // for temporary stuff
  6.   char * array_ptr = array;
  7.   unsigned pass, item;
  8.   for (pass = item_count - 1; pass; pass --)
  9.     for (item = 0; item < pass; item ++)
  10.       if (comparison(array_ptr + item_size * item, array_ptr + item_size * (item + 1)) > 0) {
  11.         // swap the items if they are inverted
  12.         memcpy(buf, array_ptr + item_size * item, item_size);
  13.         memcpy(array_ptr + item_size * item, array_ptr + item_size * (item + 1), item_size);
  14.         memcpy(array_ptr + item_size * (item + 1), buf, item_size);
  15.      }
  16.   // array is now sorted
  17.   free(buf);
  18. }
Advertisement
RAW Paste Data Copied
Advertisement