Insert sorting instance and JAVA Implementation

Source: Internet
Author: User

Insert sorting is a simple sorting method, which can be divided into direct insertion sorting and other insertion sorting methods derived from direct insertion sorting.

The basic idea of insert sorting is: in the number of groups to be sorted, suppose n-1 [n> = 2] Number is already sorted, now we need to insert the nth number into the preceding ordered number, so that the N number is in the correct order. This repeats until all the rows are sorted.

The algorithm complexity of this sort method is O (n). Its JAVA Implementation is as follows:

// Insert_sort

Publicint[] Insert_sort (Int[]
ARR ){

Int[] Intarr = arr;

IntI, j, key;

For(J = 1; j <intarr. length; j ++ ){

Key = intarr [J];

I = J-1;

While(I> = 0 & intarr [I]> key ){

Intarr [J] = intarr [I];

I --;

}

Intarr [I + 1] = key;

}

ReturnIntarr;

}

Instance:

Sort the sequence 1, 3, 2, and 5 by inserting a sort order. The sorting process is as follows:

(1) j = 1, key = 3, I = 0 ------- 1 3 2 5

(2) J = 2, key = 2, I = 1--------1 2 3 5

(3) J = 3, key =, I = 2--------1 2 3 5

In the above example, the I auto-subtraction step is omitted. The actual step is to compare intarr [J] with all the elements in front of it every time j increases by 1, when the element before intarr [J] is greater than that before intarr [J], it is exchanged with an element before it until the sorting is complete.

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.