// L-30 MCS 360 Mon 6 Apr 2020 : bubble_sort

/* We sort by swapping the largest element in the sequence to the end,
   letting the largest element bubble to the back of the vector. */

#include <iostream>
#include <cstdlib>
#include <ctime>
#include <vector>
using namespace std;

vector< pair<int,char> > random_vector ( int n );
// returns a vector of n random 2-digit numbers
// associated with lower case letters

void write_vector ( vector< pair<int,char> > v );
// writes the vector v

void vanilla_bubble_sort ( vector< pair<int,char> >& v );
// applies bubble sort to the vector v

int main()
{
   cout << "give n : ";
   int n; cin >> n;

   srand(time(0));
   vector< pair<int,char> > v = random_vector(n);
   cout << n << " random items : ";
   write_vector(v); cout << endl;

   vanilla_bubble_sort(v);

   cout << "the sorted vector : ";
   write_vector(v); cout << endl;

   return 0;
}

vector< pair<int,char> > random_vector ( int n )
{
   vector< pair<int,char> > v;

   for(int i=0; i<n; i++)
   {
      pair<int,char> p;
      p.first = 10 + (rand() % 90);
      p.second = 'a' + rand() % 26;
      v.push_back(p);
   }

   return v;
}

void write_vector ( vector< pair<int,char> > v )
{
   for(int i=0; i<v.size(); i++)
      cout << "(" << v[i].first
           << "," << v[i].second
           << ")";
}

void vanilla_bubble_sort ( vector< pair<int,char> >& v )
{
   for(int i=0; i<v.size()-1; i++)
   {
      bool sorted = true;

      for(int j=0; j<v.size()-i-1; j++)
         if(v[j].first > v[j+1].first)
         {
            pair<int,char> tmp = v[j];
            v[j] = v[j+1];
            v[j+1] = tmp;

            sorted = false;

            cout << "after " << j 
                 << " <-> " << j+1 << " : ";
            write_vector(v); cout << endl;
         }
      if(sorted) break;
   }
}
