Apex Interview Question - Sort the alphabets without using any of the native collection methods

I came across an interview question recently that caught my attention.

The ask is basically we need to sort the alphabets in ascending order without using any of the native collection methods.

I cranked up my dev console and came up with this solution.

I just wanted to put it simple and hence opted for bubble sort algorithm

Hope this helps someone.

let me know if you have a better version of this, more than happy to give you credits and include your solution.

public class AlphaSort {
    public void foobar(){
        
        String imp = 'zbdafchadbl';
        
        String[] impNew = imp.split('');
        
        Map<String, Integer> alpha = new Map<String, Integer>();
        
        alpha.put('a', 1);
        alpha.put('b', 2);
        alpha.put('c', 3);
        alpha.put('d', 4);
        alpha.put('e', 5);
        alpha.put('f', 6);
        alpha.put('g', 7);
        alpha.put('h', 8);
        alpha.put('i', 9);
        alpha.put('j', 10);
        alpha.put('k', 11);
        alpha.put('l', 12);
        alpha.put('m', 13);
        alpha.put('n', 14);
        alpha.put('o', 15);
        alpha.put('p', 16);
        alpha.put('q', 17);
        alpha.put('r', 18);
        alpha.put('s', 19);
        alpha.put('t', 20);
        alpha.put('u', 21);
        alpha.put('v', 22);
        alpha.put('w', 23);
        alpha.put('x', 24);
        alpha.put('y', 25);
        alpha.put('z', 26);
       
        for(integer i=0; i< impNew.size(); i++){
            
            for(integer j=i+1; j< impNew.size(); j++){
                
                Integer chalAt1 = alpha.get(impNew[i]); //26
                Integer chalAt2 = alpha.get(impNew[j]); //2
                if(chalAt1 > chalAt2){
                    string t = impNew[i]; //z
                    impNew[i] = impNew[j];
                    impNew[j] = t;
                }
                
            }
        }
        
        System.debug(' 🚀 ' +impNew);
    }
}
AplhaSort.cls

The route that am taking here is

  1. Create a map of alphabets and assosiate them with serial numbers.
  2. Take the first element and get it's assosiated number.
  3. Compare that with the number of every other element of the array.
  4. If the number assosiasted with the first alphabet is more than the number assosiated with the number of the next alphabet, swap them.