fork download
  1. #include <stdio.h>
  2.  
  3. void bubble_sort(int nums[], int length)
  4. {
  5. int cc=0;
  6. for(int i=length-1; i>=0; i--){
  7.  
  8. int has_sorted = 0;
  9.  
  10. for(int j=0; j<i; j++){
  11. if(nums[j] < nums[j+1]){
  12.  
  13. // swap elements
  14. cc+=1;
  15. int temp = nums[j];
  16. nums[j] = nums[j+1];
  17. nums[j+1] = temp;
  18.  
  19. has_sorted = 1;
  20. }
  21. }
  22.  
  23. if(has_sorted == 0){
  24. break;
  25. }
  26. }
  27. printf("\n比對次數:%d\n\n",cc);
  28.  
  29. }
  30.  
  31. void print_array(int nums[], int length)
  32. {
  33. for(int i=0; i<length; i++){
  34. printf("%d ", nums[i]);
  35. }
  36. printf("\n");
  37. }
  38.  
  39. int main()
  40. {
  41. int nums[6] = {9, 12, 3, 25, 34, 90};
  42. printf("before sorting:\n");
  43. print_array(nums, 6);
  44.  
  45. // call bubble sort function
  46. bubble_sort(nums, 6);
  47.  
  48. printf("after sorting:\n");
  49. print_array(nums, 6);
  50.  
  51. return 0;
  52. }
Success #stdin #stdout 0s 4484KB
stdin
Standard input is empty
stdout
before sorting:
9 12 3 25 34 90 

比對次數:13

after sorting:
90 34 25 12 9 3