java类库中Arrays的排序算法探析(基础类型)
java.util.Arrays中有非常方便的array转换为list的方法,在?Java中List与Array的转换已经提及了,这里再介绍下其中的排序算法:
在java.util.Arrays中,排序(sort)部分占的篇幅最大,大量用到了重载,一种是根据参数类型的重载,也就是如:
?
private static void sort2(float a[], int fromIndex, int toIndex) { final int NEG_ZERO_BITS = Float.floatToIntBits(-0.0f); /* * The sort is done in three phases to avoid the expense of using * NaN and -0.0 aware comparisons during the main sort.避免事实上不需要比较,如NaN,-0.0和0.0事实上相等等 */ /* * Preprocessing phase: Move any NaN's to end of array, count the * number of -0.0's, and turn them into 0.0's.预处理阶段,将NaN移到队尾,计算-0.0的个数并转换为0.0 */ int numNegZeros = 0; int i = fromIndex, n = toIndex; while(i < n) { if (a[i] != a[i]) {float swap = a[i]; a[i] = a[--n]; a[n] = swap; } else { if (a[i]==0 && Float.floatToIntBits(a[i])==NEG_ZERO_BITS) { a[i] = 0.0f; numNegZeros++; } i++; } } // Main sort phase: quicksort everything but the NaN's,主流程,和上面long的除了数组类型和元素类型不同之外完全相同sort1(a, fromIndex, n-fromIndex); // Postprocessing phase: change 0.0's to -0.0's as required。后处理阶段,将之前转换为0.0的归位为-0.0 if (numNegZeros != 0) { int j = binarySearch0(a, fromIndex, n, 0.0f); // posn of ANY zero do { j--; } while (j>=0 && a[j]==0.0f); // j is now one less than the index of the FIRST zero for (int k=0; k<numNegZeros; k++) a[++j] = -0.0f; } }
?在传入对象数组的时候,采用的是归并排序,算法和上面的快排有所区别,后面探讨。