title: Bubble sort on a two dimensional array by one column
body: <p>I have to sort a matrix by column; as input I have an one-dimensional array and O convert it into a matrix:</p>
  
  <pre><code>int arr[] = { 6, 7, 3, 1, 3, 2, 4, 4, 7, 5, 1, 1, 5, 6, 6, 4, 5 };
  </code></pre>
  
  <p>The first element in the column is the value and the second is the number of apparences. I have to sort them by the value (by the first column). This is what i have tried so far. </p>
  
  <p>histogram.h</p>
  
  <pre><code>#ifndef HISTOGRAM_H
  #define HISTOGRAM_H
  #include&lt;iostream&gt;
  class Histogram
  {
  private:
      int** matrix;
      int lines;
      void SortMatrix();
  public:
      Histogram(){ }
      Histogram(int elements[], int elementsNr);
      Histogram(int** m, int l);
      void Print();
  };
  #endif
  </code></pre>
  
  <p>histogram.cpp</p>
  
  <pre><code>#include"histogram.h"
  using namespace std;
  Histogram::Histogram(int** m, int l)
  {
      matrix=m;
      lines=l;
      SortMatrix();
  }
  
  Histogram::Histogram(int elements[], int elementsNr)
  {
      lines=0;
      //initialize matrix : elementrNr lines and 2 columns
      matrix=new int*[elementsNr];
      for(int i=0;i&lt;elementsNr;i++)
      {
          matrix[i]=new int[2];
          matrix[i][0]=INT_MIN;
          matrix[i][1]=INT_MIN;
      }
      //search each element from the array in the matrix
      bool found=false;
      for(int i=0;i&lt;elementsNr;i++)
      {
          found=false;
          for(int j=0;j&lt;elementsNr;j++)
          {
              //the element was found in the matrix ( on the first column )
              if(matrix[j][0] == elements[i])
              {
                  matrix[j][1]++;
                  found=true;
                  break;
              }
          }
          if(!found)
          {
              matrix[lines][0]=elements[i];
              matrix[lines][1]=1;
              lines++;
          }
      }
      SortMatrix();
  
  }
  void Histogram::SortMatrix()
  {
      bool flag=true;
      int temp1;
      int temp2;
      int i=0;
      for(int i=0;(i&lt;lines-1) &amp;&amp; flag;i++)
      {
          flag=false;
          if(matrix[i][0]&gt;matrix[i+1][0])
          {
              temp1=matrix[i][0];temp2=matrix[i][1];
              matrix[i][0]=matrix[i+1][0];
              matrix[i][1]=matrix[i+1][1];
              matrix[i+1][0]=temp1;matrix[i+1][1]=temp2;  
              flag=true;
          }   
      }
  }
  void Histogram::Print()
  {
  
      for(int i=0;i&lt;lines;i++)
      {
          cout&lt;&lt;matrix[i][0]&lt;&lt;" : " &lt;&lt;matrix[i][1]&lt;&lt;endl;
      }
  
  }
  </code></pre>
  
  <p>but the output for this code is:</p>
  
  <pre><code>6:3
  7:2
  3:2
  1:3
  2:1
  4:3
  5:3
  </code></pre>
  
  <p>instead:</p>
  
  <pre><code>1:3
  2:1
  3:2
  4:3
  5:3
  6:3
  7:2
  </code></pre>