Arrays类中sort源码分析

public static void sort(int[] a) {
 sort1(a, 0, a.length);
    }

 

 private static void sort1(int x[], int off, int len) {
 // Insertion sort on smallest arrays
 if (len < 7) {
     for (int i=off; i<len+off; i++)
  for (int j=i; j>off && x[j-1]>x[j]; j--)
      swap(x, j, j-1);
     return;
 }

 

 // Choose a partition element, v
 int m = off + (len >> 1);       // Small arrays, middle element
 if (len > 7) {
     int l = off;
     int n = off + len - 1;
     if (len > 40) {        // Big arrays, pseudomedian of 9
  int s = len/8;
  l = med3(x, l,     l+s, l+2*s);
  m = med3(x, m-s,   m,   m+s);
  n = med3(x, n-2*s, n-s, n);
     }
     m = med3(x, l, m, n); // Mid-size, med of 3
 }
 int v = x[m];

 // Establish Invariant: v* (<v)* (>v)* v*
 int a = off, b = a, c = off + len - 1, d = c;
 while(true) {
     while (b <= c && x[b] <= v) {
  if (x[b] == v)
      swap(x, a++, b);
  b++;
     }
     while (c >= b && x[c] >= v) {
  if (x[c] == v)
      swap(x, c, d--);
  c--;
     }
     if (b > c)
  break;
     swap(x, b++, c--);
 }

 // Swap partition elements back to middle
 int s, n = off + len;
 s = Math.min(a-off, b-a  );  vecswap(x, off, b-s, s);
 s = Math.min(d-c,   n-d-1);  vecswap(x, b,   n-s, s);

 // Recursively sort non-partition-elements
 if ((s = b-a) > 1)
     sort1(x, off, s);
 if ((s = d-c) > 1)
     sort1(x, n-s, s);
    }

    /**
     * Swaps x[a] with x[b].
     */
    private static void swap(int x[], int a, int b) {
 int t = x[a];
 x[a] = x[b];
 x[b] = t;
    }

    /**
     * Swaps x[a .. (a+n-1)] with x[b .. (b+n-1)].
     */
    private static void vecswap(int x[], int a, int b, int n) {
 for (int i=0; i<n; i++, a++, b++)
     swap(x, a, b);
    }

 

 

 

    /**
     * Returns the index of the median of the three indexed integers.
     */
    private static int med3(int x[], int a, int b, int c) {
 return (x[a] < x[b] ?
  (x[b] < x[c] ? b : x[a] < x[c] ? c : a) :
  (x[b] > x[c] ? b : x[a] > x[c] ? c : a));
    }

 


这里的快排采用了所谓的Median-of-3 partition:随机找出3个元素,并取其中中间的那个作为轴值(pivot)。效果得到了改进时间复杂度为

n*log(n) ,且是稳定的(值相同的元素相对顺序不会改变)。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值