import java.util.*;
import java.io.*;

class Sorting implements Runnable{
     class DNK implements Comparable<DNK> {
       String dnk;
       int inv;

       private int merge(char[] ar, int n){
         int res = 0;
         for(int i =0 ; i < n; i++){
             for(int j = i+1; j < n; j++)
               if(ar[j] < ar[i])
                 res ++;
         }
         return res;
       }
       DNK(String str, int m){
           dnk= str;
           char[] c = dnk.toCharArray();
           inv = merge(c,m);
       }
       public int compareTo(DNK  d){
         if(inv < d.inv)
              return -1;
           else if(inv > d.inv)
                   return 1;
           else return 0;
        }
    }

     public void run(){
       try{
           Scanner in = new Scanner(new File("sorting.in"));
           PrintWriter out = new PrintWriter(new File("sorting.out"));

           int m = in.nextInt();
           int n = in.nextInt();

          DNK[] d = new DNK[n];

           for(int i = 0; i < n  ; i++){
               String str = in.next();
               d[i] = new DNK(str, m);
           }

           Arrays.sort(d);

           for(int i = 0; i < n; i++)
               out.println(d[i].dnk);

           in.close();
           out.close();
       }  catch(Exception e){
            e.printStackTrace();
            System.exit(1);
          }
     }
     public static void main(String[] args) {
        new Thread(new Sorting()).start();
     }

}
