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
In response to the second part of you question:
Arrays.sort
in Java has guaranteed O(n log n) time complexity, as specified in the API.Try using a
TreeMap<String, Integer>
(assuming you want to sort integers) which means all entries are sorted by their string key:Output:
To sort an array and get the new order of the previous indices you could iterate over the array and add the indices as Integer objects to the map:
If you need to sort the keys by anything else but the natural order, you can add a
Comparator<String>
to theTreeMap
constructor.This is the equivalent of the JavaScript sort. The Comparator object is used as the callback function is used in JavaScript.