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/>}