fork download
  1. #include <stdio.h>
  2. #include <stdbool.h>
  3.  
  4. #define MAX 4
  5.  
  6. int list[MAX] = {8, 4, 9, 1};
  7.  
  8. void display(){
  9. int i;
  10. printf("[");
  11.  
  12. // navigate through all items
  13. for(i = 0; i < MAX; i++){
  14. printf("%d ",list[i]);
  15. }
  16.  
  17. printf("]\n");
  18. }
  19.  
  20. void bubbleSort() {
  21. int temp;
  22. int i,j;
  23.  
  24.  
  25. bool swapped = false;
  26.  
  27. // loop through all numbers
  28. for(i = 0; i < MAX-1; i++) {
  29. swapped = false;
  30.  
  31. // loop through numbers falling ahead
  32. for(j = 0; j < MAX-1-i; j++) {
  33. printf(" Items compared: [ %d, %d ] ", list[j],list[j+1]);
  34.  
  35. // check if next number is lesser than current no
  36. // swap the numbers.
  37. // (Bubble up the highest number)
  38.  
  39. if(list[j] > list[j+1]) {
  40. temp = list[j];
  41. list[j] = list[j+1];
  42. list[j+1] = temp;
  43.  
  44. swapped = true;
  45. printf(" => swapped [%d, %d]\n",list[j],list[j+1]);
  46. }else {
  47. printf(" => not swapped\n");
  48. }
  49.  
  50. }
  51.  
  52. // if no number was swapped that means
  53. // array is sorted now, break the loop.
  54. if(!swapped) {
  55. //break;
  56. }
  57.  
  58. printf("Iteration %d#: ",(i+1));
  59. display();
  60. }
  61.  
  62. }
  63.  
  64. main(){
  65. printf("Input Array: ");
  66. display();
  67. printf("\n");
  68.  
  69. bubbleSort();
  70. printf("\nOutput Array: ");
  71. display();
  72. }
Success #stdin #stdout 0s 2112KB
stdin
Standard input is empty
stdout
Input Array: [8 4 9 1 ]

     Items compared: [ 8, 4 ]  => swapped [4, 8]
     Items compared: [ 8, 9 ]  => not swapped
     Items compared: [ 9, 1 ]  => swapped [1, 9]
Iteration 1#: [4 8 1 9 ]
     Items compared: [ 4, 8 ]  => not swapped
     Items compared: [ 8, 1 ]  => swapped [1, 8]
Iteration 2#: [4 1 8 9 ]
     Items compared: [ 4, 1 ]  => swapped [1, 4]
Iteration 3#: [1 4 8 9 ]

Output Array: [1 4 8 9 ]