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

 => not swapped
 => swapped [4, 8]
 => swapped [6, 8]
 => swapped [0, 8]
 => swapped [3, 8]
 => swapped [5, 8]
 => swapped [2, 8]
 => swapped [7, 8]
 => not swapped
Iteration 1#: [1 4 6 0 3 5 2 7 8 9 ]
 => not swapped
 => not swapped
 => swapped [0, 6]
 => swapped [3, 6]
 => swapped [5, 6]
 => swapped [2, 6]
 => not swapped
 => not swapped
Iteration 2#: [1 4 0 3 5 2 6 7 8 9 ]
 => not swapped
 => swapped [0, 4]
 => swapped [3, 4]
 => not swapped
 => swapped [2, 5]
 => not swapped
 => not swapped
Iteration 3#: [1 0 3 4 2 5 6 7 8 9 ]
 => swapped [0, 1]
 => not swapped
 => not swapped
 => swapped [2, 4]
 => not swapped
 => not swapped
Iteration 4#: [0 1 3 2 4 5 6 7 8 9 ]
 => not swapped
 => not swapped
 => swapped [2, 3]
 => not swapped
 => not swapped
Iteration 5#: [0 1 2 3 4 5 6 7 8 9 ]
 => not swapped
 => not swapped
 => not swapped
 => not swapped

Output Array: [0 1 2 3 4 5 6 7 8 9 ]