首页 > 代码库 > jdk_Arrays类_排序方法_研究

jdk_Arrays类_排序方法_研究

 private static void sort1(int x[], int off, int len) {
	// Insertion sort on smallest arrays
	//长度小于7,采用冒泡排序
	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;
	}

	//长度不小于7,采用快速排序,此处为生成第一次进行划分的元素的位置m
	//第一个划分元素为 int v = x[m]
	// Choose a partition element, v
	/m的开始值为中间位置
	int m = off + (len >> 1);       // Small arrays, middle element
	//len>7,获取划分元素位置m
	if (len > 7) {
	    int l = off;		//起始位置
	    int n = off + len - 1;	//末尾位置
	    //len>40,将其分3段,然后取每段的中间(比大小)元素
	    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];

	//建立如下(v* (<v)* (>v)* v*)的序列
	// 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;
    }
    //写的很精巧,就是取x[a],x[b],x[c],这三个元素的中间元素
    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));
    }
   /**
     * 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);
    }