[英]Sort a parallel array using Arrays.sort()
是否可以使用Arrays.sort()
對數組進行Arrays.sort()
,然后使另一個相關的數組與已排序的數組位於同一位置,例如:
String arrNames[] = new String[5];
String arrCellNo[] = new String[arrNames.length];
String arrNamesSorted[] = new String[arrNames.length];
System.arraycopy(arrNames, 0, arrNamesSorted, 0, arrNames.length);
Arrays.sort(arrNamesSorted);
從這一點出發,我想對CellNo
數組進行排序,這樣,如果“人”的cellNo為“ x”,則對數組arrNames
進行排序后,他將具有相同的“ cellNo”“ x”
您不能讓Arrays.sort
以對第一個數組進行排序的方式來操作第二個數組。
解決方案是對自己的對象進行排序,這些對象包含所需的所有數據。 創建具有名稱和電話號碼屬性的Contact
類。 然后創建一個實現Comparator<Contact>
(例如ContactComparator
)以比較名稱。
然后,您將能夠對具有特定Arrays.sort
重載的 Contact
對象數組進行Arrays.sort
。
Arrays.sort(arrContacts, new ContactComparator());
所有數據將保持井井有條,因為相同的名稱仍將具有相同的單元號。
我會采用另一種方法:
創建一個新對象:
public class Person { private name; private cellNo; // Implement getters and setters }
創建一個比較器:
public MyComparator implements Comparator<Person> { public int compare(Person a, Person b) { return a.getName().compareTo(b.getName()); } }
在Person[] persons = ...
上調用Array.sort(persons, new MyComparator())
Person[] persons = ...
array
如果名稱是唯一的,請考慮使用SortedMap :
final SortedMap<String,String> nameToCellNo = new TreeMap<>();
for (int i = 0; i < arrNames.length; i++) {
nameToCellNo.put(arrNames[i], arrCellNo[i]);
}
int ctr = 0;
for (Map.Entry<String,String> entry : nameToCellNo.entrySet()) {
arrNamesSorted[ctr] = entry.getKey();
arrCellNoSorted[ctr++] = entry.getValue();
}
我發現答案中引入的一些概念很難理解,因此在我自己的解決方案中,我們采用了不受歡迎的編程方法,因為這種對代碼的交易更易於理解,並創建了冒泡排序方法,最后像這樣操縱第二個數組:
String arrNames[] = new String[5];
String arrCellNo[] = new String[arrNames.length];
String arrNamesSorted[] = new String[arrNames.length];
String arrCellNoSorted[] = new String[arrCellNo.length];
System.arraycopy(arrNames, 0, arrNamesSorted, 0, arrNames.length);
System.arraycopy(arrCellNo, 0, arrCellNoSorted, 0, arrCellNo.length);
for (int i = 0; i < arrNamesSorted.length; i++) {
for (int j = 0; j <arrNamesSorted.length-1; j++) {
if (arrNamesSorted[j].compareTo( arrNames[j+1])>0) {
String temp = arrNamesSorted[i];
arrNamesSorted[i] = arrNamesSorted[j];
arrCellNoSorted[i] = arrCellNoSorted[j];
arrNames[j] = temp;
}
}
}
可以使用內置的Arrays.sort來存檔效果,而無需為並行數組內容創建類。
注意,索引應該是一個對象數組 ,而不是原始數組 。 ( Arrays.sort(int[])
不使用比較器)
final int n = 10;
int[] values = new int[n];
Integer[] index = new Integer[n];
par_foreach(n, i -> index[i] = i);
par_foreach(n, i -> values[i] = random.nextInt(100));
Arrays.sort(index, (a, b) -> Integer.compare(values[a], values[b]));
println("values", values);
println("index", index);
print("ordered:");
foreach(n, i -> print(" " + values[index[i]]));
println();
foreach :: Num -> (Num -> void) (parallel) par_foreach :: Num -> (Num -> void)
如果您無法想象實現: https : //github.com/beenotung/javalib/blob/master /src/com/github/beenotung/javalib/Utils.java
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.