Program algorithm art and Practice classic sorting algorithm insertion sort

Source: Internet
Author: User

The basic idea of inserting a sort (insertion sort) is to insert a record to be sorted each time, by its keyword size, into the appropriate location in the previously ordered sub-file until all records are inserted.

basic ideas and pseudo-code

After j-1 the processing, a[1..j-1] has been in good order. J-Pass processing only a[j] into the appropriate position of l[1..j-1], so that A[1..J] is a sequence of orderly. To achieve this, we can use a sequential comparison method. First compare A[j] and a[j-1], if A[J-1]≤A[J], then A[1..J] has been ordered, the first time the processing is finished, otherwise exchange a[j] and a[j-1] position, continue to compare a[j-1] and a[j-2] until a certain location I (1≤i≤j-1), Make a[j]≤a[j+1]. The pseudo code is described as follows:

Algorithm: Insertsort (a,n) Input: N array a output: A1 in ascending order. For J <-2 to n do2.    X<-a[j]3.    I <-j-1                       //Line 3 to Line 7 put A[j] into a[1.....j-1] 4.    While I >0 and x <a[i] Do5.           A[I+1] <-a[i]6.           i<-i-17.           A[I+1] <-x
As shown in the procedure for inserting 4 elements into a sequence, a total of (a), (b), (c) three insertions are required. Inserts a sort of 4 elements


In the insertion sorting algorithm, we can introduce a sentinel element A[0] to write the program, which is smaller than any record in A[1..N]. So, we have a constant-∞ in the type ElementTypeof the element, which is smaller than any record that might occur. If the constant-∞ is not good in advance, it is necessary to check if the current position is 1 before deciding whether A[i] will move forward, and if the current position is 1 o'clock, the processing of the I-pass should be closed. Another option would be to put A[i] into a[0] at the beginning of the first processing, which would also guarantee the end of the I-pass process at the appropriate time.

Efficiency Analysis

Consider the complexity of algorithmic insertion_sort. For determined I, the number of internal while loops is O (i), so the entire loop body executes ∑o (i) =o (∑i), where I from 2 to N. That is, the number of comparisons is O (N2). If the input sequence is arranged from large to small, the inner while loop is i-1 times, so the entire loop body executes ∑ (i-1) =n (n-1)/2 times. So, worst case, insertion_sort to compare Ω (n^2) times. If the element type is a large record, the 5th line of the algorithm consumes a lot of time, so it is necessary to analyze the number of times the element was moved. The analysis shows that on average the 5th line executes N (n-1)/4 times, and the analysis method is the same as the bubble sort analysis. If moving an element consumes a lot of time, you can use a linked list to implement a linear table.

Insertion_sort implementation

According to the idea of inserting sort pseudo code, the implementation algorithm code is as follows:

void Insertsort (int *a,int n) {         int i,j,t,m;               for (i=1;i<n;i++)  {              t=a[i];              j=i-1;              while (j>=0 && t<a[j])  {                  a[j+1]=a[j];                  j--;              }              a[j+1]=t;          }      
We don't feel like programming style (^_^) for the above implementation codes. So the following code is &GT;_&LT;:

void Insertionsort (int *ptritems, int count) {                                                      int i, J,  K;                                                                                               for (I=1; i< count;  ++i) {                                                      k = ptritems[i];                              for (j=i-1; (j>=0) && (K<ptritems[j]); j--) ptritems[j+1] = ptritems[j];                                                                    Ptritems[j+1] = k;                                }                                              }
before testing, here is a partial code for part of the main function. where the contract n is 20 (the input array size), and the rand () function is used to make the value of the input array randomly generated. The code looks like this:

int array[n],i;           Declares an array of  Srand (Time (NULL));  for (i=0;i<n;i++) {        //Initialize array  array[i]=rand ()/1000+10;  }  printf ("Sort before:\n");  for (i=0;i<n;i++) {  printf ("%d", Array[i]);   Output  }  printf ("\ n");       Insertsort (array,n);//Sort       printf ("Sort after:\n");  for (i=0;i<n;i++)  {  printf ("%d", Array[i]);   Output  }  
in this program, the main function first initializes an array and outputs the array contents before sorting. Then, call the Insert Sort method function, and then output the sorted array contents.

In the Insert sort procedure, you first save the element you want to insert into the variable T. The variable J represents the insertion position (the ordinal of the array element is inserted), and the value is set to I-1, which indicates that the number of the current position (ordinal i) is to be inserted into the position of the ordinal i-1 (that is, the previous element).

Then, judging by the while loop, if the data with the ordinal J element is greater than the variable t (the data that needs to be inserted), the element with the ordinal j is shifted backwards and j-1 to determine if the previous data still needs to be moved backwards. Through this loop, the value of an element is found to be smaller than T, and the ordinal number of the element is J. The data is then inserted in the next element with the ordinal J.

Compile to execute this program and get the following results, as shown in.



The insertion sorting method is efficient when the data has a certain order. However, if the data is irregular, you need to move a large amount of data, which is as inefficient as the bubble sort method and the selection sort method. The insertion sort method is a sort of in situ permutation and a stable sort method. Although the insertion method is in the worst case complex θ (n^2), for small-scale inputs, the insertion order is a fast, in-place permutation method. Many complex sorting methods, in the case of small size, are sorted using the insertion sort method, such as quick sorting and bucket sorting.


About algorithmic art and practice more discussion and communication, please pay attention to this blog and Sina Weibo songzi_tea.






Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Program algorithm art and Practice classic sorting algorithm insertion sort

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.