Write a three-way fast row with your eyes closed (java)

Write a three-way fast row with your eyes closed (java)

Idea: The core of quick sorting is to compare the benchmark value. Those less than the benchmark value v are placed on the left, and those greater than the benchmark value are placed on the right to get the correct position of the benchmark value.
Therefore, an array (subscript range: [l, r]) is selected after the reference value v (here the default reference value is the first element) traversed with i, divided into four parts, less than its [l, lt] , Equal to its [lt+1, i -1], [i, rt-1] that has not been traversed yet, [rt,r] greater than it: as shown below
[l,…lt],[lt+1 ,…,I-1],i,…,[rt,…,r]

//直接展示寻找基准值的核心代码,由于三路快排考虑到等于基准值的情况,
//因此返回的是值为V的两边不为v的两个值,这里用数组返回
public int[] partition(int[] a, int l, int r) {
    
    
	//基准值
	int v = a[l]
	//遍历索引,l是基准值,直接从l+1开始遍历
	int i = l + 1;
	int lt = l;
	int rt = r + 1;

	while (i < rt) {
    
    
		if (a[i] < v) {
    
    
			swap(a,lt+1,i);
			lt++;
			i++;
		}else if (a[i] > v) {
    
    
			swap(a,rt-1.i);
			rt--;
		}else {
    
    
			i++;
		}
	}
	
	swap(a,l,lt);
	return new int[]{
    
    lt,rt};
}

Selection of the benchmark value in the Java source code:
When the size of the array is size=7, the middle element of the array is taken as the division element.
When the array size is 7<size<=40, the element with the middle size of the first, middle, and last three elements is taken as the division element.
When the size of the array size>40, 9 elements are selected more evenly from the array to be arranged, and a pseudo median is selected as the division element.

Guess you like

Origin blog.csdn.net/Beer_xiaocai/article/details/104489170