c++全ソートを実現

2292 ワード

キャリアC++コード(3)全配列
#include <assert.h>
#include <iostream>
#include <algorithm>
using namespace std;

template<typename T>
void Perm(T* pT, int n, int m)
{
    if (n == m)
    {
        for (int i=0; i<m; i++)
            cout << pT[i] << " ";
        cout << endl;
        return;
    }
    else
    {
        for (int i=m; i<n; i++)
        {
            swap(pT[m], pT[i]);
            Perm(pT, n, m+1);
            swap(pT[m], pT[i]);
        }
    }
}



class Permutation
{
public:
    enum {MAX_SIZE = 10};
    Permutation(int count)
    {
        assert(0 < count && count < MAX_SIZE);
        m_nCount = (char)count;
        for (char i=0; i<m_nCount; i++)
            m_Indexs[i] = i;
    }
    
public:
    bool ToNext();
    
    char operator[] (int n)const
    {
        assert(0 <= n && n <= m_nCount);
        return m_Indexs[n];
    }
    
private:
    char m_Indexs[MAX_SIZE];
    char m_nCount;
};

bool Permutation::ToNext()
{
    char nReverse = m_nCount-1;
    while (nReverse > 0 && m_Indexs[nReverse]<m_Indexs[nReverse-1])    
        nReverse--;    //            
    if (nReverse == 0)    //    ,        
        return false;
    
    char nSwap = m_nCount - 1;
    while (m_Indexs[nSwap] < m_Indexs[nReverse-1])
        nSwap--;    //        
    swap(m_Indexs[nReverse-1], m_Indexs[nSwap]);    //     
    reverse(m_Indexs+nReverse, m_Indexs+m_nCount);    //   
    return true;
}


int main()
{
    const int N = 3;
    Permutation perm(N);
    const char* sTests[N] = {"aaa", "bbb", "ccc"};
    do
    {
        for (int i=0; i<N; i++)
            cout << sTests[perm[i]] << " ";
        cout << endl;
    }while(perm.ToNext());
    return 0;
}