Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Collections.sort is implemented as mergesort. looking at the source, all compare conditions are <code>&gt;0</code> or <code>&lt;=0</code> which by chance treat the negative case the same as the equal case. a different sort implementation can fail.</p> <p>Per jbellis's comment, "<em>It's not quite "just luck," though -- Collections.sort is guaranteed to be "stable," meaning that equal elements must be in the same relative order post-sort. I'm not sure it's impossible to come up with a stable sort implementation that fails with this comparator, but I can't think of one off the top of my head.</em>"</p> <pre><code>private static void mergeSort(Object[] src, Object[] dest, int low, int high, int off, Comparator c) { int length = high - low; // Insertion sort on smallest arrays if (length &lt; INSERTIONSORT_THRESHOLD) { for (int i=low; i&lt;high; i++) for (int j=i; j&gt;low &amp;&amp; c.compare(dest[j-1], dest[j])&gt;0; j--) swap(dest, j, j-1); return; } // Recursively sort halves of dest into src int destLow = low; int destHigh = high; low += off; high += off; int mid = (low + high) &gt;&gt; 1; mergeSort(dest, src, low, mid, -off, c); mergeSort(dest, src, mid, high, -off, c); // If list is already sorted, just copy from src to dest. This is an // optimization that results in faster sorts for nearly ordered lists. if (c.compare(src[mid-1], src[mid]) &lt;= 0) { System.arraycopy(src, low, dest, destLow, length); return; } // Merge sorted halves (now in src) into dest for(int i = destLow, p = low, q = mid; i &lt; destHigh; i++) { if (q &gt;= high || p &lt; mid &amp;&amp; c.compare(src[p], src[q]) &lt;= 0) dest[i] = src[p++]; else dest[i] = src[q++]; } } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload