bubble.tex 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. \documentclass{article}
  2. \usepackage{verbatim}
  3. \newenvironment{code}{\footnotesize\verbatim}{\endverbatim\normalsize}
  4. \begin{document}
  5. \section{Bubble Sort in C}
  6. Bubble Sort is the probably the first sorting algorithm everyone is introduced to. Let's first include the necessary header files:
  7. \begin{code}
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <stdbool.h>
  11. \end{code}
  12. The main operation of Bubble Sort is swapping two values:
  13. \begin{code}
  14. void swap(int *x, int *y)
  15. {
  16. int t = *x;
  17. *x = *y;
  18. *y = t;
  19. }
  20. \end{code}
  21. The easiest way to remember how to implement it is when you assign something to the variable \verb|t| like \verb|int t = *x;| you are saving that thing so on the next line you can override it \verb|*x = *y;|. And after that finish the process by assigning the second variable \verb|*y = t;|.
  22. Alright, now let's implement the bubble sort itself:
  23. \begin{code}
  24. void bubble_sort(int *xs, int xs_size)
  25. {
  26. for (int i = xs_size - 1; i > 1; --i) {
  27. for (int j = 0; j < i; ++j) {
  28. if (xs[j] > xs[j + 1]) {
  29. swap(&xs[j], &xs[j + 1]);
  30. }
  31. }
  32. }
  33. }
  34. \end{code}
  35. Let's check if this bubble sort algorithm works correctly. Let's implement a function that can generate \verb|n| random numbers for testing.
  36. \begin{code}
  37. #define MAX_X_SIZE 100
  38. void generate_n_numbers(int *xs, int n)
  39. {
  40. for (int i = 0; i < n; ++i) {
  41. xs[i] = rand() % MAX_X_SIZE;
  42. }
  43. }
  44. \end{code}
  45. We also need to be able to check that the array is sorted. We can do that by iterating the array with a ``window'' of size 2 and checking if the pairs are ascending
  46. \pagebreak
  47. \begin{code}
  48. // 1 2 3 5 4 6
  49. // ^ ^ ascending
  50. // 1 2 3 5 4 6
  51. // ^ ^ ascending
  52. // 1 2 3 5 4 6
  53. // ^ ^ ascending
  54. // 1 2 3 5 4 6
  55. // ^ ^ DESCENDNIG!!!
  56. bool is_sorted(int *xs, int n)
  57. {
  58. for (int i = 0; i < n - 1; ++i) {
  59. if (xs[i] > xs[i + 1]) {
  60. return false;
  61. }
  62. }
  63. return true;
  64. }
  65. \end{code}
  66. \end{document}