/*
 *  Copyright (c) 2010 Cyrille Berger <cberger@cberger.net>
 *
 * This library is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public
 * License as published by the Free Software Foundation;
 * either version 2, or (at your option) any later version of the License.
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this library; see the file COPYING.RUNTIME.  If not, write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA 02110-1301, USA.
 *
 * The file COPYING.RUNTIME.EXCEPTION contains an exception that allow
 * to use this file with other open source license
 */

#ifndef _CAUCHY_SORT_H_
#define _CAUCHY_SORT_H_

#include <algorithm>

namespace Cauchy {
  namespace Internal {
    // http://en.wikipedia.org/wiki/Quicksort
    template<typename _T_>
    int partition(_T_& t, int left, int right, int pivotIndex)
    {
      typename _T_::Scalar pivotValue = t[pivotIndex];
      std::swap(t[pivotIndex], t[right]); // Move pivot to end
      int storeIndex = left;
      for(int i = left; i < right; ++i)
      {
        if(t[i] <= pivotValue)
        {
          std::swap(t[i], t[storeIndex]);
          storeIndex = storeIndex + 1;
        }
      }
      std::swap(t[storeIndex], t[right]); // Move pivot to its final place
      return storeIndex;
    }
    template<typename _T_>
    void quicksort(_T_& t, int left, int right)
    {
      if(right > left)
      {
         int pivotIndex = right; // left+(right-left) / 2;
         int pivotNewIndex = partition(t, left, right, pivotIndex);
         quicksort(t, left, pivotNewIndex - 1);
         quicksort(t, pivotNewIndex + 1, right);
      }
    }
  }
  Eigen::MatrixXd sort(const Eigen::MatrixXd& m, int dim = 1)
  {
    Eigen::MatrixXd s = m;
    if(dim == 1)
    {
      for(int i = 0; i < s.cols(); ++i)
      {
        Eigen::MatrixXd::ColXpr col = s.col(i);
        Internal::quicksort(col, 0, s.rows() - 1);
      }
    } else if(dim == 2)
    {
      for(int i = 0; i < s.rows(); ++i)
      {
        Eigen::MatrixXd::RowXpr row = s.row(i);
        Internal::quicksort(row, 0, s.cols() - 1);
      }
    } else {
      // TODO assert
    }
    return s;
  }
}

#endif
