[英]Why does this sort in Java 1.8
Taken from Java Puzzlers by Joshua Bloch and Neal Gafter 取自Joshua Bloch和Neal Gafter的Java Puzzlers
import java.util.*;
public class BananaBread {
public static void main(String[] args) {
Integer[] array = { 3, 1, 4, 1, 5, 9 };
Arrays.sort(array, new Comparator<Integer>() {
public int compare(Integer i1, Integer i2) {
return i1 < i2 ? -1 : (i2 > i1 ? 1 : 0);
}
});
System.out.println(Arrays.toString(array));
}
}
The expected behaviour is undefined and the text says that it returns [3, 1, 4, 1, 5, 9]. 预期的行为是未定义的,文本说它返回[3,1,4,1,5,9]。 This is true up to Java Version 1.7.
这适用于Java V1.7。 However, in Java v. 1.8, the output is the sorted list.
但是,在Java v.1.8中,输出是排序列表。
I can see that Timsort is new in Java 1.8, but I'm not sure how the algorithm can function with an inconsistent comparator such as the one given above. 我可以看到Timsort是Java 1.8中的新功能,但我不确定算法如何使用不一致的比较器(例如上面给出的)来运行。 Any help or insight into how this can be would be greatly appreciated.
任何有关如何做到这一点的帮助或见解将不胜感激。
Java 8 uses a modied merge sort. Java 8使用修改的合并排序。 The key line it uses is
它使用的关键是
// From TimSort.binarySort
while (left < right) {
int mid = (left + right) >>> 1;
if (c.compare(pivot, a[mid]) < 0) // compares for less than 0.
right = mid;
else
left = mid + 1;
}
Note: it only cares about whether you return -1 or 0 (more specifically is < 0, true or false) 注意:它只关心你是返回-1还是0(更具体地说是<0,true或false)
Your comparator is the same as 你的比较器与
return i1 < i2 ? -1 : 0;
so in all the ways that matter for this code it's correct. 所以在这个代码的所有重要方面都是正确的。
Note: if you change the code like this 注意:如果您更改此代码
return i1 > i2 ? +1 : 0;
It doesn't sort anything. 它没有任何排序。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.