Insert Sort (JAVA)

Source: Internet
Author: User

Find the I, the a[i] and a[0] to a[i-1] in order to exchange the elements smaller than it, in I from left to right changes, I left are ordered, when I reached the rightmost sorting complete.

Inserting a sort is useful for the following arrays:

    • Each element in the array is not far from its final position.
    • An ordered large array followed by a decimal group
    • The position of only a few elements in the array is incorrect

When the number of inverted is small, the insertion sort is likely to be faster than the other sorting algorithms.

 Packagesort20171111;ImportJava.util.*; Public classInsertion { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub                int[]a =New int[20]; intN; Scanner in=NewScanner (system.in); N=In.nextint ();  for(inti = 0; I < n; i++) {A[i]=In.nextint (); }                //Insert Sort         for(inti = 1; I < n; i++) {             for(intj = i; J > 0; j--) {                if(A[j] < a[j-1]) {                    inttemp; Temp=A[j]; A[J]= A[j-1]; A[j-1] =temp; }            }        }                 for(inti = 0; I < n; i++) {System.out.println (a[i]); }    }}

Insert Sort (JAVA)

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.