fork(1) download
  1. #include <cstdio>
  2. #include <iostream>
  3.  
  4. template<typename T, bool low_to_high>
  5. void bubblesort(T* x, unsigned size)
  6. {
  7. for (unsigned i = 0; i < size - 1; ++i)
  8. {
  9. for (unsigned j = 0; j < size - i - 1; ++j)
  10. {
  11. if (low_to_high ? x[j] > x[j + 1] : x[j] < x[j + 1])
  12. {
  13. T temp = x[j];
  14. x[j] = x[j + 1];
  15. x[j + 1] = temp;
  16. }
  17. }
  18. }
  19. }
  20.  
  21. void print(int* a, unsigned size)
  22. {
  23. for (unsigned i = 0; i < size - 1; ++i)
  24. {
  25. std::cout<<a[i]<<" ";
  26. }
  27.  
  28. std::cout<<a[size - 1]<<"\n\n";
  29. }
  30.  
  31. int main()
  32. {
  33. int a[12] = {0};
  34. unsigned len = sizeof(a)/sizeof(a[0]);
  35.  
  36. std::cout<<"Enter "<<len<<" numbers: ";
  37. for (unsigned i = 0; i < len; ++i)
  38. {
  39. std::cin>>a[i];
  40. std::cin.ignore();
  41. }
  42.  
  43. std::cout<<"\n\n";
  44.  
  45. bubblesort<int, true>(a, len);
  46. print(a, len);
  47.  
  48. bubblesort<int, false>(a, len);
  49. print(a, len);
  50. }
Success #stdin #stdout 0s 3344KB
stdin
1, 4, 3, 7, 2, 10, 5, 8, 11, 6, 12, 9
stdout
Enter 12 numbers: 

1 2 3 4 5 6 7 8 9 10 11 12

12 11 10 9 8 7 6 5 4 3 2 1