Skip to content

Instantly share code, notes, and snippets.

@moyashiki
Created November 12, 2013 01:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save moyashiki/7423839 to your computer and use it in GitHub Desktop.
Save moyashiki/7423839 to your computer and use it in GitHub Desktop.
Blocksort by C++. reference from http://www.geocities.jp/m_hiroi/light/pyalgo48.html .
#include <vector>
#include <iostream>
#include <algorithm>
class Blocksort
{
public:
static std::string encode(const std::string &input,int &top);
static std::string decode(const std::string &input,int top);
};
std::string Blocksort::encode(const std::string &input, int &top)
{
std::string buff,result;
buff = input + input;
std::vector<std::string> vtemp;
//巡回表
for(int i=0; i < buff.size()/2;++i){
std::string temp=buff.substr(i,input.size());
vtemp.push_back(temp);
}
//sort
std::stable_sort(vtemp.begin(),vtemp.end());
//末尾をとる
for(int i=0; i < vtemp.size();++i){
if( input == vtemp[i] ) top = i;
result += *(vtemp[i].end()-1);
}
return result;
}
std::string Blocksort::decode(const std::string &input,int top)
{
std::string result,inputs=input;
// only index sort
std::vector<int> idx(input.size());
for (int i = 0; i != idx.size(); ++i) idx[i] = i;
std::stable_sort(idx.begin(),idx.end(),
[inputs](int i1,int i2) {return inputs[i1] < inputs[i2];});
//decode
int p = top;
for(int i=0;i<input.size();++i) {
p = idx[p];
result += inputs[p];
}
return result;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment