The arrays class of Java beauty [from rookie to expert walkthrough] and its method analysis

Source: Internet
Author: User
Tags sorts

Two cyan

Personal site: zhangerqing.cn email: [Email protected] Weibo: HTTP://WEIBO.COM/XTFGGEF

This chapter mainly introduces the key methods of the Java.util.Arrays class, including how to use and implement the principle. This is an algorithm class, mainly auxiliary array class to implement some sort, search and other functions, but also support the conversion of array to list. This chapter is the beauty of Java [from rookie to expert walkthrough] series of arrays class and its methods analysis, if there are any problems, welcome to contact me through any of the above way!

Sort

This article uses jdk1.8.0_25 to test, and ask friends to note the version differences, because different JDK implementations are slightly differentiated. Arrays.sort () method, for the basic data type with Dualpivotquicksort (multi-path) to sort, for the reference type of the array, the use of mergesort (merge sort) to sort, let's talk about these two sorts of sorting algorithm.

sorting a primitive type array

Of the eight basic data types in Java, except for the Boolean, the other seven are available and require ordering, if an array is a single underlying type, such as int[] data, long data[] can be sorted directly using Arrays.sort (). For all sortable basic types, they are sorted by Dualpivotquicksort. Let's start with an example:

Package Com.adam.java.algo.arrays;import Java.util.arrays;import Org.junit.test;public class ArraysBasicTest {@ testpublic void Testsortinteger () {int data[] = {10, 8, 9, 1, 2, 5, 98, 3, 7, 66}; Arrays.sort (data), for (int i:data) {System.out.print (i + "");}} @Testpublic void Testsortchar () {char data[] = {' D ', ' B ', ' E ', ' C ', ' H ', ' A ', ' Y ', ' G ', ' I ', ' O '}; Arrays.sort (data), for (char i:data) {System.out.print (i + "");}}}

Output:

1 2 3 5 7 8 9 10 66 98

A B C D E G H I O Y

Here we have to look at the algorithm used by Arrays.sort (), we look at the next JDK source code.

/**     * Sorts the specified array into ascending numerical order.     *     * <p>implementation note:the sorting algorithm is a dual-pivot Quicksort     * by Vladimir Yaroslavskiy, Jon Bentley, and Joshua Bloch. This algorithm     * offers O (n log (n)) performance on many data sets that cause other     * quicksorts to degrade to quad Ratic performance, and is typically     * faster than traditional (One-pivot) Quicksort implementations.     *     * @param a The array to be sorted     */public    static void sort (int[] a) {        dualpivotquicksort.sort (a, 0, A.length-1, NULL, 0, 0);    }

It is found that all basic sorting is done directly using Dualpivotquicksort.sort (), so it is necessary to understand the principle of dualpivotquicksort. The basic idea is:

The number of elements from 1-47 is sorted directly using the Insert sort.

The number of elements from 47-286 is used to quickly sort by multiple routes.

If the number of elements is greater than 286, merge sort is used

Here we study the principle of the multi-channel, first of all, we review how the classic fast-line is implemented.


Classic quick-line implementation Ideas :

1. Find a middle axis, generally select the first element of the array.

2. Define two pointers, pointing to the leftmost and rightmost, and traversing from the right, if it is larger than the middle axis, the right hand moves one bit to the left, and if it is less than the middle axis, the position is reversed, and if it is less than the middle axis, the pointer moves to the right, and if it is larger than the middle axis,

3. A trip sorted down, the left side of the axis is smaller than the middle axis, the right is greater than the middle axis.

4. Recursive sub-arrays such as upper operation, instability, time complexity of the optimal situation O (NLOGN), the worst case is the basic Order O (N2). Please refer to another blog post for detailed instructions on how to use the Express line.


Multi-way fast line realization idea:

1. Select two axis P1, P2.

2. Assume p1<p2, otherwise swap.

3. The Zhongyuan array is divided into four parts: less than the middle Axis 1, greater than the middle Axis 2, between the two middle axes, the unsorted part (except for the first two axes, the other elements belong to this section).

4. After starting, the never-sorted section selects a number, compares it to two axes, and then places it in the right place, until the unsorted part has no data, ending a trip to sort.

5. Recursively handles sub-arrays, stabilizes the ordering, and the time complexity stabilizes to O (Nlogn).


To sort an array of reference types

Let's give an example of an array of user types, sorted by age, using the comparator interface here, and more about comparator, click.

Create a new user class:

Package Com.adam.java.algo.arrays;public class User {private string name;private string gender;private int age;public use R (string name, string gender, int age) {this.name = Name;this.gender = Gender;this.age = age;} /** * @return The name */public String getName () {return name;} /** * @param name * The            name to set */public void SetName (String name) {this.name = name;} /** * @return The gender */public String Getgender () {return gender;} /** * @param gender * The            gender to set */public void Setgender (String gender) {This.gender = gender;} /** * @return The Age */public int Getage () {return age;} /** * @param age * The age to            set */public void Setage (int.) {this.age = age;}}

Build a sort class again:

Package Com.adam.java.algo.arrays;import Java.util.comparator;public class Usercomparator implements comparator< user> {@Overridepublic int compare (user O1, user O2) {return o1.getage ()-O2.getage ();}}

Test:

Package Com.adam.java.algo.arrays;import Java.util.arrays;public class Arraystest {public static void main (string[] args) {user[] users = new User[]{new user ("egg", "male", "+"), New User ("Kity", "Female", +), new user ("Pole", "male", 23) , New User ("Jack", "male", 28)}; Arrays.sort (Users, New Usercomparator ()); for (User user:users) {System.out.println ("name:" + user.getname () + ", Age:" +user.getage ());}}}

Output:

Name:pole, Age:23name:kity, Age:25name:egg, Age:26name:jack, age:28

This is a simple example of ordering an array of reference types, in JDK1.8, the sorting of reference types, the algorithm of merging sorts.

In JDK1.8, the Parallelsort () is introduced for the sorting method, and each sort () has a corresponding parallel ordering method, with Parallelsort () after the number of elements in the array is greater than 2 13 times (8196).

Search

Searches for an already ordered array using a binary search, if present, returns the position of key in the array, if not present, returns a negative number, the value is:-insertion point-1, for example:

Suppose a sorted array is: 1,6,8,10,12, if key is 7, then the return value is-3, because 7 should be inserted between 6 and 8, so the insertion point is 2 (subscript starts from 0), so the return value is -2-1=-3.

Arraytolist this aspect is to convert an array into a list form, noting that instead of simply turning all the elements in the array into all the elements of the new list, the entire array is transformed into an element of the list.
/** * Returns a fixed-size list backed by the specified array.  (Changes to * The returned list "write through" to the array.) This method acts * as bridge between array-based and collection-based APIs, in * combination with {@link Collectio  N#toarray}.     The returned list is * Serializable and implements {@link randomaccess}. * * <p>this method also provides a convenient-to-Create a fixed-size * list initialized to contain sever     Al elements: * <pre> * list<string> stooges = arrays.aslist ("Larry", "Moe", "Curly"); * </pre> * @param <T> The class of the objects in the array * @param A, the array by which the LI    St'll be backed * @return A list view of the specified array */@SafeVarargs @SuppressWarnings ("VarArgs")    public static <T> list<t> aslist (T ... a) {return new arraylist<> (a); }

According to the note, the new list returned is a fixed-length list, we already know that its length is 1, and it is not possible to add or delete elements on the line, otherwise reported: Java.lang.UnsupportedOperationException exception. Why is this? Because the ArrayList here is not our usual java.util.ArrayList class, but an inner class of the arrays class, because it inherits the Abstractlist, all can and list convert, but do not have add and remove operations. Copyofarrays.copyof () is used to copy the array, return a completely new array, you can pass in a parameter to define the size of the new array, if the incoming number is less than the original array length, then directly cut off the original array of excess, if the value passed in is greater than the original array, The extra portion of the new array complements the default value (for the int type, 0).
For the Java.util.Arrays class, for the time being introduced here, interested readers can read more JDK source code, have any questions, welcome to contact me: Personal site: zhangerqing.cn e-mail: [email protected] Weibo:/http Weibo.com/xtfggef

The arrays class of Java beauty [from rookie to expert walkthrough] and its method analysis

Related Article

Contact Us

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.