bubble_sort.c 796 B

12345678910111213141516171819202122232425262728293031323334
  1. // C program for implementation of Bubble sort
  2. #include <stdio.h>
  3. int compare_count = 0; // 记录比较次数
  4. void swap(int* x, int* y){
  5. int temp = *x;
  6. *x = *y;
  7. *y = temp;
  8. }
  9. void bubbleSort(int arr[], int n){
  10. int i, j, compared_count = 0;
  11. for (i = 0; i < n - 1; i++)
  12. for (j = 0; j < n - i - 1; j++){
  13. compare_count++;
  14. if (arr[j] > arr[j + 1])
  15. swap(&arr[j], &arr[j + 1]);
  16. }
  17. }
  18. void printArray(int arr[], int size){
  19. for (int i = 0; i < size; i++)
  20. printf("%d ", arr[i]);
  21. printf("\n");
  22. }
  23. int main(){
  24. int arr[] = { 5, 1, 4, 2, 8 };
  25. int n = sizeof(arr) / sizeof(arr[0]);
  26. bubbleSort(arr, n);
  27. printf("Compared count: %d, sorted: \n", compare_count);
  28. printArray(arr, n);
  29. return 0;
  30. }