Advertisement
rihardmarius

bubble sort - array

Dec 7th, 2013
98
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.06 KB | None | 0 0
  1. #include <iostream>
  2. #include <array>
  3. #define N 10
  4.  
  5. using namespace std;
  6.  
  7. void swap (int& a, int& b)
  8. {
  9.     int aux = a;
  10.     a = b;
  11.     b = aux;
  12. }
  13.  
  14. void bubble_sort2 (array<int,N>& a) // recomendado
  15. {
  16.     bool swapped;
  17.     for (int i = 0; i < N-1; i++)
  18.     {
  19.         swapped = false;
  20.         for (int j=N-1; j > i; j--)
  21.             if (a.at(j) < a.at(j-1))
  22.             {
  23.                 swap (a.at(j),a.at(j-1));
  24.                 swapped = true;
  25.             }
  26.         if (not swapped)
  27.             break;
  28.     }
  29. }
  30.  
  31. void bubble_sort (array<int,N>& a) // y el ganador es este
  32. {
  33.     int c = 0;
  34.     for (int i = N-1; i > 0; i--)
  35.         for (int j=0; j < i; j++)
  36.         {
  37.             if (a.at(j) > a.at(j+1))
  38.                 swap (a.at(j),a.at(j+1));
  39.             c++;
  40.         }
  41.     cout << c << endl;
  42. }
  43.  
  44. void printarray (array<int,N>& a)
  45. {
  46.     for (int i=0; i<N; i++)
  47.         cout << a.at(i) << " ";
  48.     cout << "\n";
  49. }
  50.  
  51. int main()
  52. {
  53.     array<int,N> arr = {6,7,8,9,10,5,4,3,2,1};
  54.     bubble_sort(arr);
  55.     printarray(arr);
  56.  
  57.     return 0;
  58. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement