Advertisement
Guest User

Macro Bubble Sort

a guest
Jan 14th, 2013
35
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.76 KB | None | 0 0
  1. //
  2. //  Sort.h
  3. //  Sort
  4. //
  5. //  Created by me on 1/14/13.
  6. //  Copyright (c) 2013 me. All rights reserved.
  7. //
  8.  
  9. #ifndef Sort_Sort_h
  10. #define Sort_Sort_h
  11.  
  12. #define CREATE_SORT_FUNC_WITH_TYPE(__TYPE__, __FUNC_DIRECTION__) \
  13.     static void sort_##__TYPE___##__FUNC_DIRECTION__(__TYPE__ *array, u_int32_t count) { \
  14.         u_int32_t i = 0; \
  15.         u_int32_t j = 0; \
  16.         __TYPE__ temp = 0; \
  17.         for (i = 0; i < count; i++) { \
  18.             for (j = 0; j < i; j++) { \
  19.                 if (_compare_##__FUNC_TYPE___##__FUNC_DIRECTION__(array[i], array[j])) { \
  20.                     temp = array[i]; \
  21.                     array[i] = array[j]; \
  22.                        array[j] = temp; \
  23.                 } \
  24.             } \
  25.         } \
  26.     }
  27.  
  28. #define DEFINE_COMPARE_FUNC(__FUNC_TYPE__, __FUNC_DIRECTION__, a, b) static inline bool _compare_##__FUNC_TYPE___##__FUNC_DIRECTION__(__FUNC_TYPE__ a, __FUNC_TYPE__ b)
  29.  
  30. #define SORT(__TYPE__, __FUNC_DIRECTION__, array, count) sort_##__TYPE___##__FUNC_DIRECTION__(array, count)
  31.  
  32. #endif
  33.  
  34.  
  35. //
  36. //  main.c
  37. //  Sort
  38. //
  39. //  Created by me on 1/14/13.
  40. //  Copyright (c) 2013 me. All rights reserved.
  41. //
  42.  
  43. #include <stdlib.h>
  44. #include <stdio.h>
  45. #include <stdbool.h>
  46. #include <time.h>
  47. #include "Sort.h"
  48.  
  49. DEFINE_COMPARE_FUNC(int, ascending, a, b) {
  50.     return (a < b);
  51. }
  52.  
  53. CREATE_SORT_FUNC_WITH_TYPE(int, ascending)
  54.  
  55.  
  56. int main(int argc, const char * argv[]) {
  57.     u_int32_t count = 10;
  58.     int *array = malloc(count * sizeof(*array));
  59.     srand((unsigned int)time(NULL));
  60.     for (u_int32_t i = 0; i < count; i++) {
  61.         array[i] = rand();
  62.     }
  63.    
  64.     SORT(int, ascending, array, count);
  65.    
  66.     for (u_int32_t i = 0; i < count; i++) {
  67.         printf("%d\n", array[i]);
  68.     }
  69.    
  70.     return 0;
  71. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement