# Java. Ui. Arrays array efficiency optimization

Source: Internet
Author: User

(1) sorting of basic data type Arrays, such as Arrays. sort (int. A fine-tuned quick sorting is adopted. This algorithm is adapted from Jon L. bentley and M. engineering a Sort Function co-authored by Douglas McIlroy ", Software-Practice and Experience Vol. 23 (11) P. 1249-1265 (November 1993 ). This algorithm provides n * log (n) performance on many datasets, which causes other quick sorting to reduce the quadratic performance.
The source code for optimizing the quick sort algorithm in JDK is as follows:

 The code is as follows: Copy code /*** Sorts the integer array of the specified range in ascending order.* X [] array to be sorted* Off: Starts Sorting from the off element of the array.* Len array length*/Private static void sort1 (int x [], int off, int len ){// Optimization 1: in small-scale (size <7) arrays, direct insertion of sorting is more efficient than fast sorting.If (len <7 ){For (int I = off; I off & x [j-1]> x [j]; j --)Swap (x, j, j-1 );Return; }// Optimization 2: carefully select the partitioning element, that is, pivot// If it is a small-scale array (size <= 7), take the intermediate element as the pivot.// If it is an array of medium size (7 = 40), take a pseudo-medium number (in the middle of the number s) from the nine specified numbers)Int m = off + (len> 1 );If (len> 7 ){Int l = off;Int n = off + len-1;If (len> 40 ){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 ); }Int v = x [m];// Optimization 3: each pivot v division forms a form such as ( v )*// Stage 1: form an array of 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 --); }// Phase 2, swap the pivot and element equal to the pivot to the center of the arrayInt 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 );// Phase 3: recursive sorting and pivot are not equal to element intervalsIf (s = B-a)> 1)Sort1 (x, off, s );If (s = d-c)> 1)Sort1 (x, n-s, s );    }

★Optimization 1: in small-scale (size <7) arrays, direct insertion sorting is more efficient than fast sorting.

No sorting is the optimal comparison-based internal sorting summary in any case. The O (N ^ 2) level sorting seems to be much worse than all advanced sorting. But this is not the case. The sort () algorithm in Arrays provides a good example. When the size of the array to be sorted is very small (the size threshold in JDK is INSERTIONSORT_THRESHOLD = 7), direct insertion sorting is better than fast sorting and merging sorting is better.

This is simple. The array size is small, and the comparison times of simple algorithms are not much higher than those of advanced algorithms. On the contrary, advanced algorithms, such as fast sorting and merge sorting, use recursive operations, resulting in a higher operating cost.

★Optimization 2: carefully select the partitioning element, that is, pivot.

There is one worst case of fast sorting, that is, sort into the worst-efficiency start sorting (see "exchange sorting"). The main cause of this situation is that the selection of pivot cannot divide the entire array into two roughly equal parts. For example, for an array with basic order, selecting the first element as the pivot will produce this regionalization.

In this case, we can see how Arryas. sort () chooses pivot for us.

● For small-scale arrays (size <= 7), take the intermediate element as the pivot.

● If it is an array of medium size (7 = <size <= 40), take the number of the intermediate size in the number at the first, middle, and last positions of the array as the pivot.
● If it is a large-scale array (size> 40), take a pseudo-medium number (the number s in the middle of the nine specified numbers)

When the size is small, this method can avoid the smaller decimal or larger number of arrays as pivot. It is worth mentioning that, in a large scale, we first look for nine pieces of data in the array (we can find that the positions of the nine pieces of data are evenly distributed across the array through the source code ); then find the median for every three data records, and then find a median for the three medians as the pivot.

Think about it, this carefully selected pivot makes the worst case of fast sorting a very small probability event.

★Optimization 3: Based on pivot v, an array is formed, such as (<v) * v * (> v) *.

The general fast sorting algorithm moves the pivot element to the middle of the array. All elements before pivot are less than or equal to pivot, and all subsequent elements are greater than pivot. However, elements equal to the pivot cannot be moved to a position near the pivot. This is greatly optimized in the Arrays. sort () algorithm.

Here is an example to illustrate the optimization details of Arrays: 15, 93, 15, 41, 6, 15, 22, 7, 15, and 20.

Pivot for the first time: v = 15

Phase 1 forms an array of v * (<v) * (> v) * v:

15, 15, 7, 6, 41, 20, 22, 93, 15, 15

We found that the elements equal to the pivot move to both sides of the array. Elements smaller than pivot and those larger than pivot are also separated.

Phase 2: Swap the pivot and element equal to the pivot to the position in the middle of the array

7, 6, 15, 15, 15, 15, 41, 20, 22, 93

Stage 3: recursive sorting and pivot are not equal to element ranges {7, 6} and {41, 20, 22, 93 }. Think about it. For arrays with many repeated elements, this optimization can undoubtedly achieve better efficiency.

(1) sorting of Object Arrays, such as Arrays. sort (Object. A modified merge sorting is adopted. It also has several highlights of optimization.

The source code for improving the merge sorting algorithm in JDK is as follows:

 The code is as follows: Copy code /*** Sort the array of objects in the specified range in ascending order.* Src [] original to be sorted array* Dest [] destination to be sorted array* Low: Lower bound position of the array to be sorted* Upper bound position of the high to-be-arranged array* Off: Starts Sorting from the off element of the array.*/Private static void mergeSort (Object [] src,Object [] dest,Int low,Int high,Int off ){Int length = high-low;// Optimization 1: sorting of small-sized arrays. The efficiency of directly inserting the sorting is higher than that of merging.// The scale must be within INSERTIONSORT_THRESHOLD = 7.If (length low &&(Comparable) dest [j-1]). compareTo (dest [j])> 0; j --)Swap (dest, j, j-1 );Return;        }// Recursively sort half of dest elements and assign them to srcInt destLow = low;Int destHigh = high;Low + = off;High + = off;Int mid = (low + high)> 1;MergeSort (dest, src, low, mid,-off );MergeSort (dest, src, mid, high,-off );// Optimization 2: If the highest element in the low sublist is smaller than the lowest element in the high sublist, the merge is ignored.// If you want to merge the two ends of low ~ (Middle-1), middle ~ High is ordered, that is, src [mid-1] = src [mid].// You only need to set the src low ~ The dest value corresponding to the high value does not need to be merged.If (Comparable) src [mid-1]). compareTo (src [mid]) <= 0 ){System. arraycopy (src, low, dest, destLow, length );Return;        }// Merge the two parts of src and assign them to destFor (int I = destLow, p = low, q = mid; I = high | p

★Optimization 1: Fast sorting above
★Optimization 2: If the highest element in the lower sublist is smaller than the lowest element in the higher sublist, the merge is ignored. This optimization measure undoubtedly greatly improves the efficiency of the basic ordered sequence.

Related Keywords:
Related Article

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## 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.