Sort Algorithm (3) insert and sort

Source: Internet
Author: User

When talking about sorting, there will be no less insertion sorting algorithms. It is really classic and simple.
Algorithm: insert sorting
Insertion_sort ()
For j = 2 to A. length
Do key = A [j]
I = J-1
While (I> 0 & A [I]> key)
Do A [I + 1] = A [I]
I = I-1;
A [I + 1] = key

 

I learned it only after studying the playing cards ..

C ++ code:

// The insertion sorting is obviously O (N ^ 2), but it is better in a certain condition, for example, O (n) is used to sort the order in basic order ), O (nlgn) is used for fast sorting ). In addition, it is ranked in worst_case, and // It is also O (N ^ 2 ). // Code for testing insertsort by Ouyang # include <iostream> using namespace STD; void insertsort (int * a, int Len) {// sort from the second card, by default, the first piece of cards is arranged. // cards are divided into three parts: // 1. arranged, from 1 to J-1 // 2. j // 3. pre-arranged J + 1 to N // If the row in the hand is larger than the pre-arranged I, it will be placed after I // if it is smaller than I, then compare it with the previous one of I until I = 1 // then insert this card to I + 1. For (Int J = 2; j <= Len; j ++) {int key = A [J]; int I = J-1; while (I >=1 & A [I]> key) {A [I + 1] = A [I]; I --;} A [I + 1] = Key ;}} int main () {int array [9] = {null }; int Len = sizeof (array)/sizeof (INT); insertsort (array, Len); For (Int J = 1; j <= Len; j ++) cout <array [J] <"; cout <Endl; return 0 ;}

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.