Facebook
From Rude Meerkat, 5 Years ago, written in Plain Text.
Embed
Download Paste or View Raw
Hits: 253
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <errno.h>
  4. #include <string.h>
  5. /** Our old friend die from ex17. */
  6. void die(const char *message)
  7. {
  8.  if(errno) {
  9. MAIN
  10. PREVIOUS
  11. NEXT
  12. HELP
  13. Follow
  14. @lzsthw
  15.  if(errno) {
  16.  perror(message);
  17.  } else {
  18.  printf("ERROR: %sn", message);
  19.  }
  20.  exit(1);
  21. }
  22. // a typedef creates a fake type, in this
  23. // case for a function pointer
  24. typedef int (*compare_cb)(int a, int b);
  25. /**
  26.  * A classic bubble sort function that uses the
  27.  * compare_cb to do the sorting.
  28.  */
  29. int *bubble_sort(int *numbers, int count, compare_cb cmp)
  30. {
  31.  int temp = 0;
  32.  int i = 0;
  33.  int j = 0;
  34.  int *target = malloc(count * sizeof(int));
  35.  if(!target) die("Memory error.");
  36.  memcpy(target, numbers, count * sizeof(int));
  37.  for(i = 0; i < count; i++) {
  38.  for(j = 0; j < count - 1; j++) {
  39.  if(cmp(target[j], target[j+1]) > 0) {
  40.  temp = target[j+1];
  41.  target[j+1] = target[j];
  42.  target[j] = temp;
  43.  }
  44.  }
  45.  }
  46.  return target;
  47. }
  48. int sorted_order(int a, int b)
  49. {
  50.  return a - b;
  51. }
  52. int reverse_order(int a, int b)
  53. {
  54.  return b - a;
  55. }
  56. int strange_order(int a, int b)
  57. {
  58.  if(a == 0 || b == 0) {
  59.  return 0;
  60.  } else {
  61.  return a % b;
  62.  }
  63. }
  64. /**
  65.  * Used to test that we are sorting things correctly
  66.  * by doing the sort and printing it out.
  67.  */
  68. void test_sorting(int *numbers, int count, compare_cb cmp)
  69. {
  70.  int i = 0;
  71.  int *sorted = bubble_sort(numbers, count, cmp);
  72.  if(!sorted) die("Failed to sort as requested.");
  73.  for(i = 0; i < count; i++) {
  74.  printf("%d ", sorted[i]);
  75.  }
  76.  printf("n");
  77.  free(sorted);
  78. }
  79. int main(int argc, char *argv[])
  80. {
  81.  if(argc < 2) die("USAGE: ex18 4 3 1 5 6");
  82.  int count = argc - 1;
  83.  int i = 0;
  84.  char **inputs = argv + 1;
  85.  int *numbers = malloc(count * sizeof(int));
  86.  if(!numbers) die("Memory error.");
  87.  for(i = 0; i < count; i++) {
  88.  numbers[i] = atoi(inputs[i]);
  89.  }
  90.  test_sorting(numbers, count, sorted_order);
  91.  test_sorting(numbers, count, reverse_order);
  92.  test_sorting(numbers, count, strange_order);
  93.  free(numbers);
  94.  return 0;
  95. }
  96.