Sorting Algorithm Review (3) -- insert sorting

Source: Internet
Author: User

 

(1) Principle:

The first element is regarded as sorted, and the second element is stored in a temporary variable key,

If the first element is greater than the second element, move the first element to the second element;

In this way, the key can be inserted at the original position of the first element.

The insert method, as its name implies, is to first locate a location and then insert it in.

 

(2) Example:

 

(3) c ++ implementation

# Include <iostream> # include <cstdlib> # include <cstdio> using namespace STD; // int A [100]; // use insert_sort (A, 100 ); not insert_sort (A, 99) // void insert_sort (int * a, int N) {// assert (! = NULL & n> 0); For (Int J = 1; j <n; ++ J) {int key = A [J]; // temporarily Save the element to be inserted. Int I = J-1; while (I> = 0 & A [I]> key) // there must be a position to insert. The purpose of the loop is to move all elements smaller than J in the following table as long as they are larger than a [J. {A [I + 1] = A [I]; -- I;} A [I + 1] = key;} void print (int * a, int N) {for (INT I = 0; I <n; ++ I) {printf ("% 2D", a [I]) ;}printf ("\ n ");} int main () {int A [] = {, 99,-,}; insert_sort (A, sizeof (a)/sizeof (* )); print (A, sizeof (a)/sizeof (* A); Return 0 ;}

References:

[1] http://www.algolist.net/Algorithms/Sorting/Insertion_sort

[2] http://baike.baidu.com/view/396887.htm

[3] http://www.personal.kent.edu /~ Rmuhamma/algorithms/myalgorithms/sorting/insertionsort.htm

[4] http://video.sina.com.cn/v/ B /80012377-1642346981.html

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.