fork download
  1. // C program for implementation of Bubble sort
  2. #include <stdio.h>
  3.  
  4. // Swap function
  5. void swap(int* arr, int i, int j)
  6. {
  7. int temp = arr[i];
  8. arr[i] = arr[j];
  9. arr[j] = temp;
  10. }
  11.  
  12. // A function to implement bubble sort
  13. void bubbleSort(int arr[], int n)
  14. {
  15. int i, j;
  16. for (i = 0; i < n - 1; i++)
  17.  
  18. // Last i elements are already
  19. // in place
  20. for (j = 0; j < n - i - 1; j++)
  21. if (arr[j] > arr[j + 1])
  22. swap(arr, j, j + 1);
  23. }
  24.  
  25. // Function to print an array
  26. void printArray(int arr[], int size)
  27. {
  28. int i;
  29. for (i = 0; i < size; i++)
  30. printf("%d ", arr[i]);
  31. printf("\n");
  32. }
  33.  
  34. // Driver code
  35. int main()
  36. {
  37. int arr[] = { 5, 1, 4, 2, 8 };
  38. int N = sizeof(arr) / sizeof(arr[0]);
  39. bubbleSort(arr, N);
  40. printf("Sorted array: ");
  41. printArray(arr, N);
  42. return 0;
  43. }
  44.  
Success #stdin #stdout 0s 5264KB
stdin
1
457
1
87
1
320
2
3
4
stdout
Sorted array: 1 2 4 5 8