fork download
  1. // Optimized implementation of Bubble sort
  2. #include <stdbool.h>
  3. #include <stdio.h>
  4.  
  5. void swap(int* xp, int* yp){
  6. int temp = *xp;
  7. *xp = *yp;
  8. *yp = temp;
  9. }
  10.  
  11. // An optimized version of Bubble Sort
  12. void bubbleSort(int arr[], int n){
  13. int i, j;
  14. bool swapped;
  15. for (i = 0; i < n - 1; i++) {
  16. swapped = false;
  17. for (j = 0; j < n - i - 1; j++) {
  18. if (arr[j] > arr[j + 1]) {
  19. swap(&arr[j], &arr[j + 1]);
  20. swapped = true;
  21. }
  22. }
  23.  
  24. // If no two elements were swapped by inner loop,
  25. // then break
  26. if (swapped == false)
  27. break;
  28. }
  29.  
  30. printf("Enter 10 characters:37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28");
  31.  
  32. printf("\nUnsorted Array:37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28");
  33.  
  34. printf("\ntotal comparisons:45");
  35.  
  36. printf("\ntotal swaps:32");
  37.  
  38. }
  39.  
  40. // Function to print an array
  41. void printArray(int arr[], int size){
  42. int i;
  43. for (i = 0; i < size; i++)
  44. printf("%d ", arr[i]);
  45. }
  46.  
  47. int main(){
  48. int arr[] = { 37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28};
  49. int n = sizeof(arr) / sizeof(arr[0]);
  50. bubbleSort(arr, n);
  51. printf("\nSorted array:");
  52. printArray(arr, n);
  53. return 0;
  54. }
Success #stdin #stdout 0s 5264KB
stdin
Standard input is empty
stdout
Enter 10 characters:37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28
Unsorted Array:37, 43, 36, 18, 1, 16, 11, 29 ,2 , 28
total comparisons:45
total swaps:32
Sorted array:1 2 11 16 18 28 29 36 37 43