Search code examples
javaarrayssortingrecursionradix

Radix sort Java using 2 dimensional array recursive


I've been trying to implement Radix sort in Java over the last few days, but I can't get it right. I know there are solutions out there with arrayLists, but I need to do it with a 2-dimensional array and recursive for my "homework". My Problem is, that I can't put the elements in my 2d array, no matter what. Here's what I got so far:

public class ElfSort{
    public static int[] sort(int[] packages, int digit){
      //new 2d array with 10 "buckets"
      int[][] d=new int[10][];
      //temporary array 
      int[] tmp;
      if(digit>=0){
         //going through array and try to put each element into a bucket using putIn()
         for(int i=0; i<packages.length; i++){
             putIn(d[packages[i]/pot(digit)%10],packages[i]);
         }
         digit--;
         for(int i=0; i<10; i++) sort(d[i],digit);
      }
      for(int i=0; i<10; i++){
          tmp=d[i];
          for(int j=0; j<tmp.length; j++) packages[j]=tmp[j];
      }
      return packages;
    }
    private static int pot(exp){
      if(exp==0) return 1;
      return 10*pot(exp-1);
    }
    private static int[] putIn(int[] place, int nr){
      int[] nplace=new int[place.length+1];
      for(int i=0; i<place.length; i++) nplace[i]=place[i];
      nplace[nplace.length-1]=nr;
      return nplace;
    }    
}

Solution

  • so for everyone who searches an answer for this, i finally got it right:

    public class Elfsort{
       public static int[] sort(int[] packages, int digit){
          if(packages.length<2) return packages;
          if(digit>=0){
             int[][] d=new int[10][];
             int tmp=-1;
             for(int i:packages){
                 tmp=i/pot(digit);
                 d[tmp%10]=putIn(d[tmp%10],i);
             }
             digit--;
             int a=0;
             for(int i=0; i<10; i++){
                 sort(d[i],digit);
                 for(int j:d[i]){
                     packages[a++]=j;
                 }
             }
          }
          return packages;
      }
    }