fork download
  1. #include <iostream>
  2. using namespace std;
  3.  
  4. // Function to print n elements of the array arr
  5. void printArray(int arr[], int n)
  6. {
  7. for (int i = 0; i < n; i++)
  8. cout << arr[i] << " ";
  9. }
  10.  
  11. // perform bubble sort on arr[]
  12. void bubbleSort(int arr[], int n)
  13. {
  14. // run (n - 1) times
  15. for (int k = 0; k < n - 1; k++)
  16. {
  17. // flag to detect that the list is already sorted
  18. bool sorted = true;
  19.  
  20. // last k items are already sorted, so inner loop can
  21. // avoid looking at the last k items
  22. for (int i = 0; i < n - 1 - k; i++)
  23. {
  24. if (arr[i] > arr[i + 1])
  25. {
  26. swap(arr[i], arr[i + 1]);
  27. sorted = false;
  28. }
  29. }
  30. // stop algorithm if the inner loop didn’t do any swap
  31. if (sorted)
  32. break;
  33. }
  34. }
  35.  
  36. int main()
  37. {
  38. int arr[] = { 3, 5, 8, 4, 1, 9, -2 };
  39. int n = sizeof(arr) / sizeof(arr[0]);
  40.  
  41. bubbleSort(arr, n);
  42.  
  43. printArray(arr, n);
  44.  
  45. return 0;
  46. }
  47.  
Success #stdin #stdout 0s 3468KB
stdin
Standard input is empty
stdout
-2 1 3 4 5 8 9