Insert Sort Java Implementation

Source: Internet
Author: User

 PackageKpp.sort;/*** Currently to be inserted element data[i], if DATA[I]>=DATA[I-1], then the order is normal, i++ processing the next element * if DATA[I]<DATA[I-1], first save data[i] to temp, Find the right place to insert K, the element order from K to i-1 * move to the left * Insert temp into k *
Analysis

The direct insert sort is a stable sort.
When a file is not in the same state, the time it takes to insert the order directly differs greatly.
If the initial state of the file is a positive sequence, then each record to be inserted only need to compare one time to find the appropriate location to insert, the algorithm time complexity of O (n), this is the best case.
If the initial state is reversed, then the first I want to insert records need to compare i+1 times to find a suitable location to insert, so the time complexity of O (N2), which is the worst case.
The average time complexity of the direct insert sort is O (n^2). * @authorKPP*/ Public classInsertsort { Public Static voidMain (string[] args) {//TODO auto-generated Method Stub intArray[] = {5,3,2,67,1,8}; Insertsort (array); for(intK:array) {System.out.println (k); } } Private Static intInsertsort (inta[]) { intLen =a.length; for(inti = 1;i < len;i++){ if(A[i] < a[i-1]){ inttemp =A[i]; intJ; //Method 1: Locate the insertion position and move the uniform right//Find insertion Position for(j = I-1;j >=0&&temp < a[j];j--); //Unify Move Right for(intK = i-1;k >= j+1;k--) {a[k+1]=A[k]; } //Insert the correct positionA[J+1] =temp; //Method 2: Compare one, move one /*For (j = i-1;j >=0;j--) {if (temp < a[j]) {a[j+1] = a[j]; }else{break; }} a[j+1] = temp;*/ } } return0; }}

Insert Sort Java Implementation

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.