[英]How to call java built-in TimSort on an array of primitive data types
In java, The methodArrays.sort
has two overloads (that I am interested in, in this post) one is for primitive types and the other is for reference types.在 Java 中,方法
Arrays.sort
有两个重载(我感兴趣,在这篇文章中)一个用于原始类型,另一个用于引用类型。 They use different sorting algorithms.他们使用不同的排序算法。
How can I use the algorithm used for reference types to sort primitive types (without converting them to reference types neither using lists)如何使用用于引用类型的算法对原始类型进行排序(不将它们转换为引用类型,也不使用列表)
The method Arrays.sort(int[])
uses Dual-Pivot Quicksort .方法
Arrays.sort(int[])
使用 Dual-Pivot Quicksort 。
The method Arrays.sort(Object[])
uses TimSort .方法
Arrays.sort(Object[])
使用TimSort 。
If I have an int[] array = { /* some values here */ };
如果我有一个
int[] array = { /* some values here */ };
, How can I sort it using TimSort? , 如何使用 TimSort 对其进行排序? (I know that using
Integer[] array = { /* some values here */ };
will use TimSort but I do not want that because of the overhead of using Objects instead of primitive data and there might be some boxing and unboxing later) (我知道使用
Integer[] array = { /* some values here */ };
将使用 TimSort 但我不希望那样做,因为使用对象而不是原始数据的开销,并且稍后可能会有一些装箱和拆箱)
Or is it not efficient to use TimSort on primitive data?还是在原始数据上使用 TimSort 效率不高?
I had found a class for TimSort java.util.TimSort but I couldn't access it in my codes.我为 TimSort java.util.TimSort找到了一个类,但我无法在我的代码中访问它。
The reason for this question is that Quicksort has a worst case of O(n^2)
and I had faced an array that exploited that case.这个问题的原因是 Quicksort 有一个
O(n^2)
的最坏情况,我遇到了一个利用这种情况的数组。 While TimSort has a worst case of (n log(n))
and a best case of O(n)
虽然 TimSort 有
(n log(n))
的最坏情况和O(n)
的最佳情况
UPDATE:更新:
I am actually interested in just having a built-in method for TimSort, it does not need to be Arrays.sort
.我实际上只是对 TimSort 有一个内置方法感兴趣,它不需要是
Arrays.sort
。 If there is any other built-in method to sort primitive data types using TimSort it is totally welcome.如果有任何其他内置方法可以使用 TimSort 对原始数据类型进行排序,那么它是完全受欢迎的。
java built-in TimSort
and ComparableTimSort
do not work with arrays of primitive data types, it's only sort method expects array of objects java 内置的
TimSort
和ComparableTimSort
不适用于原始数据类型的数组,它只是排序方法需要对象数组
static void sort(Object[] a, int lo, int hi, Object[] work, int workBase, int workLen);
While DualPivotQuicksort
has sort methods for primitive types, like:虽然
DualPivotQuicksort
具有原始类型的排序方法,例如:
static void sort(char[] a, int left, int right,
char[] work, int workBase, int workLen);
static void sort(int[] a, int left, int right,
int[] work, int workBase, int workLen);
Update.更新。 Although it's not the answer for original question about
Arrays.sort
, geeksforgeeks has implementation of timsort for c++/java/python3/c#.虽然它不是关于
Arrays.sort
原始问题的答案,但geeksforgeeks已经为 c++/java/python3/c# 实现了 timsort。 Method prototype for java is: java的方法原型是:
public static void timSort(int[] arr, int n);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.