Java Insert Sort

Source: Internet
Author: User

First, the basic concept

The basic operation of inserting a sort is to insert a data into the ordered data that is already sorted, so as to get a new sequential data with a number plus one, the algorithm is suitable for the ordering of a small amount of data, and the time complexity is O (n^2). is a stable sorting method. The insertion algorithm divides the array to be sorted into two parts: the first part contains all the elements of the array, except for the last element (where an array has more space to insert), and the second part contains only that element (that is, the element to be inserted). After the first part is sorted, the last element is inserted into the first part of the sequence.

Second, Java code implementation
 Public classInsertsort { Public Static voidInsersort (int[] Array) {        if(array==NULL|| Array.length<2){            return; }         for(inti=1;i<array.length;i++) {//The default first element is an ordered queue, and the second element starts with a loop insert           intPosition=array[i];//set the second element as the data to be inserted           intJ=i-1;  while(j>=0&&position<Array[j]) {Array[j+1]=ARRAY[J];//if the number of inserts is less than the J element, move the number of J backwardj--; } array[j+1]=position;//Insert        }    }     Public Static voidMain (String ags[]) {int[] Array={2,6,4,7,3,-1};        Insersort (array);  for(inti=0;i<array.length;i++) {System.out.print (Array[i]+" "); }    }}
View Code

Third, performance analysis
    • Stability
    • Space complexity O (1)
    • Time complexity O (n2)
    • Worst case: Reverse order, need to move n (n-1)/2 elements
    • Best case: Positive order, no moving element required

Java Insert Sort

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.