Just a couple small c programs.

mysort.c 1.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <stddef.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <fcntl.h>
  5. int counter;
  6. int *resize_array(int *a, size_t new_size)
  7. {
  8. int *save;
  9. save = realloc(a, new_size);
  10. if (save == NULL) {
  11. fprintf(stderr, "Memory exhuasted\n");
  12. exit(EXIT_FAILURE);
  13. }
  14. return save;
  15. }
  16. void swap(int *a, int *b){
  17. int old_a = *a;
  18. *a = *b;
  19. *b = old_a;
  20. }
  21. int partition(int *array, int left, int right, int pivot){
  22. int pivot_value = array[pivot];
  23. swap(&array[pivot], &array[right]);
  24. int storeIndex = left;
  25. for(int i = left; i < right; i++){
  26. if (array[i] < pivot_value){
  27. swap(&array[i], &array[storeIndex]);
  28. storeIndex++;
  29. }
  30. }
  31. swap(&array[storeIndex], &array[right]);
  32. return storeIndex;
  33. }
  34. void quicksort(int *array, int left, int right){
  35. if (left < right){
  36. int pivot = right;
  37. pivot = partition(array, left, right, pivot);
  38. quicksort(array, left, pivot - 1);
  39. quicksort(array, pivot + 1, right);
  40. }
  41. }
  42. int main()
  43. {
  44. int size = 1;
  45. int *numbers = malloc(size * sizeof *numbers);
  46. int *temp = malloc(size * sizeof *temp);
  47. int error;
  48. /// Loop through stdin stream grabbing `size` numbers each iteration
  49. while ((error = fread(temp, sizeof *numbers, 1, stdin))){
  50. // Should not happen if EOF has been reached or we have loaded all data
  51. // May happen if we reached EOF at exactly size [didn't find clear documention], in which case next iteration should catch it
  52. if (error != 0){
  53. numbers[size - 1] = temp[0];
  54. size++;
  55. numbers = resize_array(numbers, size * sizeof *numbers);
  56. }
  57. }
  58. size--;
  59. quicksort(numbers, 0, size - 1);
  60. for (int i = 0; i < size; i++){
  61. printf("%i\n", numbers[i]);
  62. }
  63. free(temp);
  64. free(numbers);
  65. return 0;
  66. }