Java 同时排序两个数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23339015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sorting two arrays simultaneously
提问by Vedant Chandra
I'm learning and understanding Java now, and while practising with arrays I had a doubt. I wrote the following code as an example:
我现在正在学习和理解 Java,在练习数组时我有一个疑问。我写了以下代码作为示例:
class example
{
public static void main(String args[])
{
String a[] = new String[] {"Sam", "Claudia", "Josh", "Toby", "Donna"};
int b[] = new int[] {1, 2, 3, 4, 5};
for(int n=0;n<5;n++)
{
System.out.print (a[n] + "...");
System.out.println (b[n]);
}
System.out.println (" ");
java.util.Arrays.sort(a);
for(int n=0;n<5;n++)
{
System.out.print (a[n] + "...");
System.out.println (b[n]);
}
}
In a nutshell, this class created two arrays with five spaces each. It fills one with names of characters from the West Wing, and fills the other with numbering from one to five. We can say that the data in these two strings corresponds to each other.
简而言之,这个类创建了两个数组,每个数组有五个空格。它用西翼人物的名字填充一个,并用从一到五的编号填充另一个。我们可以说这两个字符串中的数据是相互对应的。
Now, the program sorts the array with the names in it using Arrays.sort()
. After printing the array again, you can see that while the names are now in alphabetical order, the numbers do not correspond anymore as the second array is unchanged.
现在,程序使用Arrays.sort()
. 再次打印数组后,您可以看到虽然名称现在按字母顺序排列,但由于第二个数组未更改,因此数字不再对应。
How can I shuffle the contents of the second array to match the sort requirements of the first?The solution must also be flexible to allow for changes in the scope and size of the program. Please do not post any answers asking me to change my methodology with the arrays, or propose a more 'efficient' way of doing things. This is for educational purposed and I'd like a straight solution to the example code provided. Thanks in advance!
如何打乱第二个数组的内容以匹配第一个数组的排序要求?解决方案还必须灵活,以允许更改程序的范围和大小。请不要发布任何要求我改变数组方法的答案,或者提出一种更“有效”的做事方式。这是出于教育目的,我想要提供的示例代码的直接解决方案。提前致谢!
EDIT: I do NOT want to create an additional class, however I think some form of sorting through nested loops might be an option instead of Arrays.sort().
编辑:我不想创建额外的类,但是我认为通过嵌套循环进行排序的某种形式可能是一个选项,而不是 Arrays.sort()。
采纳答案by Prashant Gurav
Below is the code without using any Map
Collection, but if you want to use Map
then it becomes very easy. Add both the arrays into map and sort it.
下面是没有使用任何Map
集合的代码,但是如果你想使用Map
它就变得很容易了。将两个数组添加到 map 中并对其进行排序。
public static void main(String args[]) {
String a[] = new String[] {
"Sam", "Claudia", "Josh", "Toby", "Donna"
};
int b[] = new int[] {
1, 2, 3, 4, 5
};
for (int n = 0; n < 5; n++) {
System.out.print(a[n] + "...");
System.out.println(b[n]);
}
System.out.println(" ");
//java.util.Arrays.sort(a);
/* Bubble Sort */
for (int n = 0; n < 5; n++) {
for (int m = 0; m < 4 - n; m++) {
if ((a[m].compareTo(a[m + 1])) > 0) {
String swapString = a[m];
a[m] = a[m + 1];
a[m + 1] = swapString;
int swapInt = b[m];
b[m] = b[m + 1];
b[m + 1] = swapInt;
}
}
}
for (int n = 0; n < 5; n++) {
System.out.print(a[n] + "...");
System.out.println(b[n]);
}
}
回答by JB Nizet
You should not have two parallel arrays. Instead, you should have a single array of WestWingCharacter
objects, where each object would have a field name
and a field number
.
你不应该有两个并行数组。相反,您应该有一个WestWingCharacter
对象数组,其中每个对象都有一个 fieldname
和一个 field number
。
Sorting this array by number of by name would then be a piece of cake:
按名称的数量对这个数组进行排序将是小菜一碟:
Collections.sort(characters, new Comparator<WestWingCharacter>() {
@Override
public int compare(WestWingCharacter c1, WestWingCharacter c2) {
return c1.getName().compareTo(c2.getName();
}
});
or, with Java 8:
或者,使用 Java 8:
Collections.sort(characters, Comparator.comparing(WestWingCharacter::getName));
Java is an OO language, and you should thus use objects.
Java 是一种面向对象的语言,因此您应该使用对象。
回答by Alexis C.
What you want is not possible because you don't know internally how Arrays.sort
swap the elements in your String array, so there is no way to swap accordingly the elements in the int array.
您想要的是不可能的,因为您不知道内部如何Arrays.sort
交换 String 数组中的元素,因此无法相应地交换 int 数组中的元素。
You should create a class that contains the String
name and the int
position as parameter and then sort this class only with the name, providing a custom comparator to Arrays.sort
.
您应该创建一个包含String
名称和int
位置作为参数的类,然后仅使用名称对此类进行排序,为Arrays.sort
.
If you want to keep your current code (with 2 arrays, but this not the ideal solution), don't use Arrays.sort
and implement your own sorting algorithm. When you swap two names, get the index of them and swap the two integers in the other array accordingly.
如果您想保留当前代码(有 2 个数组,但这不是理想的解决方案),请不要使用Arrays.sort
和实现您自己的排序算法。当您交换两个名称时,获取它们的索引并相应地交换另一个数组中的两个整数。
回答by Pablo Francisco Pérez Hidalgo
You have to ZIP your two arrays into an array which elements are instances of a class like:
您必须将两个数组压缩到一个数组中,该数组的元素是类的实例,例如:
class NameNumber
{
public NameNumber(String name, int n) {
this.name = name;
this.number = n;
}
public String name;
public int number;
}
And sort that array with a custom comparator.
并使用自定义比较器对该数组进行排序。
Your code should be something like:
你的代码应该是这样的:
NameNumber [] zip = new NameNumber[Math.min(a.length,b.length)];
for(int i = 0; i < zip.length; i++)
{
zip[i] = new NameNumber(a[i],b[i]);
}
Arrays.sort(zip, new Comparator<NameNumber>() {
@Override
public int compare(NameNumber o1, NameNumber o2) {
return Integer.compare(o1.number, o2.number);
}
});
回答by NRKirby
The arrays are not linked in any way. Like someone pointed out take a look at
数组没有以任何方式链接。就像有人指出的那样看看
SortedMap
http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html
SortedMap
http://docs.oracle.com/javase/7/docs/api/java/util/SortedMap.html
TreeMap
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
TreeMap
http://docs.oracle.com/javase/7/docs/api/java/util/TreeMap.html
回答by Ravi Midathala
Here is the answer for your query.
这是您查询的答案。
public class Main {
public static void main(String args[]){
String name[] = new String[] {"Sam", "Claudia", "Josh", "Toby", "Donna"};
int id[] = new int[] {1, 2, 3, 4, 5};
for ( int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
int dtmp=0;
String stmp=null;
if (id[i] > id[j]) {
dtmp = rate[i];
id[i] = id[j];
id[j] = dtmp;
stmp = name[i];
name[i]=name[j];
name[j]=stmp;
}
}
}
System.out.println("Details are :");
for(int i=0;i<n;i++){
System.out.println(name[i]+" - "+id[i]);
}
}
}
回答by Rok Kralj
Some people propose making a product type. That is feasible only if the amount of elements is small. By introducing another object you add object overhead (30+ bytes) for each element and a performance penalty of a pointer (also worsening cache locality).
有些人建议制作产品类型。只有当元素数量很少时,这才是可行的。通过引入另一个对象,您为每个元素增加了对象开销(30 多个字节)和指针的性能损失(也会恶化缓存局部性)。
Solution without object overhead
没有对象开销的解决方案
Make a third array. Fill it with indices from 0
to size-1
. Sort this array with comparator function polling into the array according to which you want to sort.
制作第三个数组。用从0
到的索引填充它size-1
。使用比较器函数轮询将此数组排序到您要排序的数组中。
Finally, reorder the elements in both arrays according to indices.
最后,根据索引对两个数组中的元素重新排序。
Alternative solution
替代方案
Write the sorting algorithm yourself. This is not ideal, because you might make a mistake and the sorting efficiency might be subpar.
自己编写排序算法。这并不理想,因为您可能会犯错误并且排序效率可能低于标准。
回答by Gaurav londhe
import java.util.*;
class mergeArrays2
{
public static void main(String args[])
{
String a1[]={"Sam", "Claudia", "Josh", "Toby", "Donna"};
Integer a2[]={11, 2, 31, 24, 5};
ArrayList ar1=new ArrayList(Arrays.asList(a1));
Collections.sort(ar1);
ArrayList ar2=new ArrayList(Arrays.asList(a2));
Collections.sort(ar2);
System.out.println("array list"+ar1+ " "+ar2);
}
}