Sort----Insert Sort (C # implementation)

Source: Internet
Author: User

Algorithm steps: (from small to large)

1: Compares the first element with the second element, if the first element is less than or equal to the second element, does not do the processing, and continues to compare the second and third elements.

If the third element is less than the second element, save the element to be moved (the third element), move the second element back one bit, compare the first element with the third element, see if the first element needs to move, loop, find the first element that does not need to be moved, or No. 0 element, insert the previously saved element into that position.

classProgram {Static voidMain (string[] args) {            varNumbers =New int[]{5,5,6,1,4,7,2,9}; varResult=insortSort (numbers); }         Public Static int[] Insortsort (int[] numbers) {            inttemp =0;  for(inti =0; I < numbers. Length-1; i++)            {               if(numbers[i]<=numbers[i+1])                   Continue; Temp= Numbers[i +1];//Temp Saves the number to move forward, preventing the number from being overwritten                 for(intj = i; J >=0; j--)//numbers from element I to No. 0 element for elements that may be moved backwards                {                    if(temp <= numbers[j])//Numbers[j] need to move backward one positionNumbers[j +1] = Numbers[j];//Numbers[j+1] has been moved, or saved in temp, so no data is lost                    Else{numbers[j+1] = temp;//J+1 is the location to insert                         Break; }                    if(J = =0)//the case of the smallest valuenumbers[0] =temp; }            }            returnnumbers; }    }

Sort----Insert Sort (C # implementation)

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.