java源碼分析:Arrays.sort

來源:互聯網
上載者:User

標籤:elements   成績   ogr   nat   而在   cal   tutorial   mat   quicksort   

  1   2   3 仔細分析java的Arrays.sort(version 1.71, 04/21/06)後發現,java對primitive(int,float等原型資料)數組採用快速排序,對Object對象數組採用歸併排序。  4   對這一區別,sun在<<The Java Tutorial>>中做出的解釋是:  5   The sort operation uses a slightly optimized merge sort algorithm that is fast and stable:  6    * Fast: It is guaranteed to run in n log(n) time and runs substantially faster on nearly sorted lists. Empirical tests showed it to be as fast as a highly optimized quicksort. A quicksort is generally considered to be faster than a merge sort but isn‘t stable and doesn‘t guarantee n log(n) performance.  7   * Stable: It doesn‘t reorder equal elements. This is important if you sort the same list repeatedly on different attributes. If a user of a mail program sorts the inbox by mailing date and then sorts it by sender, the user naturally expects that the now-contiguous list of messages from a given sender will (still) be sorted by mailing date. This is guaranteed only if the second sort was stable.  8   也就是說,最佳化的歸併排序既快速(nlog(n))又穩定。  9   對於對象的排序,穩定性很重要。比如成績單,一開始可能是按人員的學號順序排好了的,現在讓我們用成績排,那麼你應該保證,本來張三在李四前面,即使他們成績相同,張三不能跑到李四的後面去。 10   而快速排序是不穩定的,而且最壞情況下的時間複雜度是O(n^2)。 11   另外,對象數組中儲存的只是對象的引用,這樣多次移位並不會造成額外的開銷,但是,對象數組對比較次數一般比較敏感,有可能對象的比較比單純數的比較開銷大很多。歸併排序在這方面比快速排序做得更好,這也是選擇它作為對象排序的一個重要原因之一。 12   排序最佳化:實現中快排和歸併都採用遞迴方式,而在遞迴的底層,也就是待排序的數組長度小於7時, 直接使用冒泡排序,而不再遞迴下去。 13   分析:長度為6的數組冒泡排序總比較次數最多也就1+2+3+4+5+6=21次,最好情況下只有6次比較。而快排或歸併涉及到遞迴調用等的開銷,其時間效率在n較小時劣勢就凸顯了,因此這裡採用了冒泡排序,這也是對快速排序極重要的最佳化。 14   /*快速排序*/ 15   private static void sort1(int x[], int off, int len) { 16   // Insertion sort on smallest arrays 17     if (len < 7) { 18       for (int i=off; i<len+off; i++) 19       for (int j=i; j>off && x[j-1]>x[j]; j--) 20           swap(x, j, j-1); 21           return; 22     } 23   // Choose a partition element, v 24   int m = off + (len >> 1); // Small arrays, middle element 25   if (len > 7) { 26   int l = off; 27   int n = off + len - 1; 28   if (len > 40) { // Big arrays, pseudomedian of 9 29   int s = len/8; 30   l = med3(x, l, l+s, l+2*s);//取後三個參數中的中間值 31   m = med3(x, m-s, m, m+s); 32   n = med3(x, n-2*s, n-s, n); 33   } 34   m = med3(x, l, m, n); // Mid-size, med of 3 35   } 36   int v = x[m]; 37   // Establish Invariant: v* (<v)* (>v)* v* 38   int a = off, b = a, c = off + len - 1, d = c; 39   while(true) { 40   while (b <= c && x[b] <= v) { 41   if (x[b] == v) 42   swap(x, a++, b); 43   b++; 44   } 45   while (c >= b && x[c] >= v) { 46   if (x[c] == v) 47   swap(x, c, d--); 48   c--; 49   } 50   if (b > c) 51   break; 52   swap(x, b++, c--); 53   } 54   // Swap partition elements back to middle 55   int s, n = off + len; 56   s = Math.min(a-off, b-a ); vecswap(x, off, b-s, s); 57   s = Math.min(d-c, n-d-1); vecswap(x, b, n-s, s); 58   // Recursively sort non-partition-elements 59   if ((s = b-a) > 1) 60   sort1(x, off, s); 61   if ((s = d-c) > 1) 62   sort1(x, n-s, s); 63   } 64   /*歸併排序*/ 65   private static void mergeSort(Object[] src, 66   Object[] dest, 67   int low, 68   int high, 69   int off) { 70   int length = high - low; 71   // Insertion sort on smallest arrays 72   if (length < INSERTIONSORT_THRESHOLD) { 73   for (int i=low; i<high; i++) 74   for (int j=i; j>low && 75   ((Comparable) dest[j-1]).compareTo(dest[j])>0; j--) 76   swap(dest, j, j-1); 77   return; 78   } 79   // Recursively sort halves of dest into src 80   int destLow = low; 81   int destHigh = high; 82   low += off; 83   high += off; 84   int mid = (low + high) >>> 1; 85   mergeSort(dest, src, low, mid, -off); 86   mergeSort(dest, src, mid, high, -off); 87   // If list is already sorted, just copy from src to dest. This is an 88   // optimization that results in faster sorts for nearly ordered lists. 89   if (((Comparable)src[mid-1]).compareTo(src[mid]) <= 0) { 90   System.arraycopy(src, low, dest, destLow, length); 91   return; 92   } 93   // Merge sorted halves (now in src) into dest 94   for(int i = destLow, p = low, q = mid; i < destHigh; i++) { 95   if (q >= high || p < mid && ((Comparable)src[p]).compareTo(src[q])<=0) 96   dest[i] = src[p++]; 97   else 98   dest[i] = src[q++]; 99   }100   }

 

java源碼分析:Arrays.sort

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.