fork download
  1. // Bubble sort in C
  2.  
  3. #include <stdio.h>
  4.  
  5. // perform the bubble sort
  6. void bubbleSort(int array[], int size) {
  7.  
  8. // loop to access each array element
  9. for (int step = 0; step < size - 1; ++step) {
  10.  
  11. // loop to compare array elements
  12. for (int i = 0; i < size - step - 1; ++i) {
  13.  
  14. // compare two adjacent elements
  15. // change > to < to sort in descending order
  16. if (array[i] > array[i + 1]) {
  17.  
  18. // swapping occurs if elements
  19. // are not in the intended order
  20. int temp = array[i];
  21. array[i] = array[i + 1];
  22. array[i + 1] = temp;
  23. }
  24. }
  25. }
  26. }
  27.  
  28. // print array
  29. void printArray(int array[], int size) {
  30. for (int i = 0; i < size; ++i) {
  31. printf("%d ", array[i]);
  32. }
  33. printf("\n");
  34. }
  35.  
  36. int main() {
  37. int data[] = {-2, 45, 0, 11, -9};
  38.  
  39. // find the array's length
  40. int size = sizeof(data) / sizeof(data[0]);
  41.  
  42. bubbleSort(data, size);
  43.  
  44. printf("Sorted Array in Ascending Order:\n");
  45. printArray(data, size);
  46. }
Success #stdin #stdout 0s 5280KB
stdin
Standard input is empty
stdout
Sorted Array in Ascending Order:
-9  -2  0  11  45