Insert sort of Base algorithm

Source: Internet
Author: User

The insertion sort is the most basic sort method, with a time complexity of O (N2).

The basic idea is to assume that a[0, ... j-1] is a sub-array that has been ordered, by comparing the a[j] with the preceding element, and inserting a[j] into the sorted sub-array.

The simple implementation of the insertion in the C language is sorted as follows:

1 /*Insert Sort C language implementation, time complexity O (n2)*/2 /*A is the array to sort, and Len is the length of the arrays*/3 voidInsert_sort (intA[],intLEN)4 {5     intI, J, key;6      for(j=1; j<len; J + +)7     {8Key =A[j];9i = j1;Ten          while(i>0&& a[i]>key) One         { Aa[i+1] =A[i]; ---i; -         } thea[i+1] =key; -     } -}

The test code is as follows:

1#include <stdio.h>2 3 #defineMAXSIZE 104 5 /*Insert Sort C language implementation, time complexity O (n2)*/6 /*A is the array to sort, and Len is the length of the arrays*/7 voidInsert_sort (intA[],intLEN)8 {9     intI, J, key;Ten      for(j=1; j<len; J + +) One     { AKey =A[j]; -i = j1; -          while(i>0&& a[i]>key) the         { -a[i+1] =A[i]; ---i; -         } +a[i+1] =key; -     } + } A  at intMain () - { -     intA[maxsize]; -     inti; -printf"Please input the num:\n"); -      for(i=0; i<maxsize; i++) in     { -scanf"%d",&a[i]); to     } +printf"before the sort:\n"); -      for(i=0; i<maxsize; i++) the     { *printf"%d", A[i]); $     }Panax Notoginsengprintf"\ n"); -      the Insert_sort (A, MAXSIZE); +  Aprintf"After the sort:\n"); the      for(i=0; i<maxsize; i++) +     { -printf"%d", A[i]); $     } $printf"\ n"); -  -}

Insert sort of Base algorithm

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.