Search code examples
javaarrayssortingtime-complexitycomparable

java: sort array1 based on array2


Thanks for the help from Zirak In my previous post i implemented the following in JavaScript:

var arr1 =[0,1,2,3];
var arr2 =["ac", "bc", "ad", "e"];
var result = arr1 .sort(function(i, j){return arr2[i].localeCompare(arr2[j])})
document.write(result );

The way to achieve this is quite compact in JavaScript, can a java implementation of this be also achieved by such simplicity? I could only think of implementing the Comparable interface like the following:

public class testCompare {
    public static String[] arr2={"ac", "bc", "ad", "e"};
    public static Obj[] arr1={new Obj(0), new Obj(1), new Obj(2), new Obj(3)};
    static class Obj implements Comparable{
            int index=0;
            public Obj(int i){
                    index=i;
            }
            @Override
            public int compareTo(Object o) {
                    return arr2[index].compareTo(arr2[((Obj)o).index]);
            }
     }
}

but if the array have X many items, then I will have to create X many Objs, is there another way that I could achieve this more simply? Another question is, if I do the above method what would be the time complexity for the sorting both in java and in JavaScript, are they all O(n^2)? Thanks a lot


Solution

  • public class MyComparator implements Comparator<Integer> {
        @Override
        public int compare(Integer i1, Integer i2) {
            return arr2[i1.intValue()].compareTo(arr2[i2.intValue()]);
        }
    }
    
    Arrays.sort(arr1, new MyComparator());
    

    This is the equivalent of the JavaScript sort. The Comparator object is used as the callback function is used in JavaScript.