我有一個叫做apple的類,它包含3個值,分別爲int x
,int y
和int weight
。然後我創建了一個蘋果類型對象的數組。現在我想根據重量排序對象數組,這意味着具有最低權重的蘋果對象應該是第一個等等。在java中排序對象數組的最快方法
我知道有很多方法可以通過使用Arrays.sort等或比較器來實現。
我想知道在Java中做這種排序的最快方法是什麼?可能有一個案件,我有500,000個對象,所以我想知道我應該使用哪種類型,更重要的是哪種方法會給我最好的方法。我甚至用Hoare分區寫了我自己的快速排序。
代碼爲蘋果類
public class Apple {
public int x;
public int y;
public int weight;
public Apple(int a, int b, int w) {
x = a;
y = b;
weight = w;
}
}
代碼主類
public class main {
static Apple[] appleArray;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int size = sc.nextInt();
int totalApples = sc.nextInt();
appleArray = new Edge[totalApples];
int x = 10;
int y = 20;
int w = 30;
for(int i = 0; i < size; i ++){
appleArray[i] = new Apple(x,y,w);
x++;
y++;
w++;
}
//Now i want to sort array of apple objects based on weight
}
}
如果你想要最快的排序,你應該知道不同的算法速度取決於數據的性質和分佈。我相信「寫和衡量績效」是你的問題的唯一正確答案。 Collections.sort很可能會做得很好。 –
我懷疑你只給出這個代碼作爲例子,但是對這個特定的主要方法按權重排序的最快方法是什麼都不做 - 權重已經隨着數組索引而增加。 –
是的,它只是一個例子,他們可能是隨機@AndyTurner,雖然 – user1010101