#include<iostream>
#include<string>
#include<vector>
using namespace std;
struct PAIR
{
string s;
string::size_type count;
};
void sort_vector(vector<PAIR>&pp) { PAIR temp; for(vector<PAIR>::size_type a=0;a!=pp.size();a++) { for(vector<PAIR>::size_type b=a+1;b!=pp.size();b++) { if(pp[a].count>pp[b].count) { temp=pp[a]; pp[a]=pp[b]; pp[b]=temp; } } } }
//冒泡排序
void bubble_sort(vector<PAIR> &pp)
{
PAIR temp;
for(vector<PAIR>::size_type a=0;a < pp.size()-1;a++)//外循环控制排序的总趟数
{
for(vector<PAIR>::size_type b=0;b<pp.size()-a-1;b++)//内循环控制一趟排序的进行
{
if(pp[b].count > pp[b+1].count)
{
temp=pp[b];
pp[b]=pp[b+1];
pp[b+1]=temp;
}
}
}
}
int main()
{
int n,m,i,k;
string str;
while(cin>>n>>m && n<=50 && m<=100)
{
vector<PAIR> pair;
for(i=0;i!=m;i++)
{
cin>>str;
k=0;
//求逆序数
for(string::size_type a=0;a!=n-1;a++)
{
for(string::size_type b=a+1;b!=n;b++)
{
if(str[a]>str[b])k++;
}
}
str[n]='\0';
PAIR p={str,k};
pair.push_back(p);
}
bubble_sort(pair);
for(vector<PAIR>::size_type a=0;a!=pair.size();a++)
{
cout<<pair[a].s<<endl;
}
}
}