Java-Sorting a 2-D array quickly
I have a 2D string array consisting of values like as
{ "Home","0.1256784"
"Contact","-0.56789"
"Refer","1.36589"
"Next","3.678456" }
I have to sort the array based upon the second element(double value) and obtain a result such as like
{"Contact","-0.56789"
"Home","0.1256784"
"Refer","1.36589"
"Next","3.678456" }
I have used some bubble sort code to sort it and it works, but and i have to know how can i make the sorting more efficient than my one in faster manner.I tried some code posted previously for the questions related to mine but i can't get the task done.
My Code:String tt="",tk="";
for(int i=1;i<myarray.length;i++)
{
for(int j=1;j<myarray.length-1;j++)
{
if(Double.parseDouble(myarray[i][1])&开发者_JS百科lt;Double.parseDouble(myarray[j][1]))
{
tk=myarray[i][1];
tt=myarray[i][0];
myarray[i][1]=myarray[j][1];
myarray[i][0]=myarray[j][0];
myarray[j][1]=myarray;
myarray[j][0]=myarray;
}
}
}
public class Sort2D {
public static void main(String args[]) {
String ss[][] = {
{"Home", "0.1256784"},
{"Contact", "-0.56789"},
{"Refer", "1.36589"},
{"Next", "3.678456"}
};
Arrays.sort(ss, new Comparator<String[]>() {
public int compare(String[] s1, String[] s2) {
double d1 = Double.parseDouble(s1[1]);
double d2 = Double.parseDouble(s2[1]);
return Double.compare(d1, d2);
}
});
for (String[] s : ss) {
System.out.println(s[0] + ": " + s[1]);
}
}
}
If it's a 2d array you can use Array.sort(String[], Comparator<String[]> comparator)
and pass a custom comparator, which compares the 2nd element of the sub array.
You can use Arrays.sortsort(Object[] a, Comparator c)
and let java take care of it. You may find this link useful
Alternative approach: you could copy the data to a TreeMap (in case all double values are unique) and let the map to the sorting:
Map<Double, String> map = new TreeMap<Double, String>();
for (String[] row:myArray) {
map.put(Double.parseDouble(row[1]), row[1]);
The entrysets iterator now returns the values in ascending sort order.
精彩评论