bubble.c 871 B

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. //bubble.c
  2. //famous bubble sort
  3. //implement the swap algorithm with pointers
  4. #include <stdio.h>
  5. #define MAX 9
  6. //function prototypes
  7. void printValues();
  8. void sort();
  9. void swap(int*, int*);
  10. int values[] = {7, 3, 9, 4, 6, 1, 2, 8, 5};
  11. int main(){
  12. printf("Before: \n");
  13. printValues();
  14. sort();
  15. printf("After: \n");
  16. printValues();
  17. return(0);
  18. } // end main
  19. // prints values[] by increasing index
  20. void printValues(){
  21. printf("[");
  22. int i = 0;
  23. for (i = 0; i < MAX; i++){
  24. printf("%d ", values[i]);
  25. }
  26. printf("]\n");
  27. }
  28. // implements ascending order bubble sort on values[]
  29. void sort(){
  30. int i, j = 0;
  31. for (i = 0; i < MAX - 1; i++){
  32. for (j = 0; j < MAX - 1; j++){
  33. if (values[j] > values [j + 1]){
  34. swap(&values[j], &values[j + 1]);
  35. printValues();
  36. }
  37. }
  38. }
  39. }
  40. // swap function
  41. void swap(int* a, int* b){
  42. int t = 0;
  43. t = *a;
  44. *a = *b;
  45. *b = t;
  46. }