Insert sorting (C #)

Source: Internet
Author: User
Insert sorting (C #)

 

Insert sorting is an effective algorithm for sorting a small number of elements. the working mechanism of insertion sorting is similar to that of many cards. when we started to touch the cards, our left hand was empty,
Card faces face down on the table. next, touch a card from the table and insert it to the correct position of a card on the left hand. in order to find the correct position of this card, you need to move it from the right to the existing card in your hand
Comparison on the left. At any time, the cards on the left are arranged in order, and these cards were originally top cards in the deck on the table.
 

 

 

The code is implemented as follows:

/// <Summary> <br/> // sort by insertion (ascending) <br/> // </Summary> <br/> Public static int [] insertionsort (INT [] needsortarray) <br/>{< br/> for (INT I = 1; I <needsortarray. length; I ++) <br/>{< br/> int key = needsortarray [I]; // equivalent to [current card], here, the key is temporarily saved. </P> <p> // compare the current card with the card in the hand. <br/> Int J = I-1; <br/> while (j> = 0 & Key <needsortarray [J]) <br/>{< br/> // move elements behind <br/> needsortarray [J + 1] = needsortarray [J]; <br/> j --; <br/>}</P> <p> // J + 1 (because the while loop on the top has made another judgment) that is, the position where the current card is inserted. <br/> needsortarray [J + 1] = key; <br/>}</P> <p> return needsortarray; <br/>}

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.