Algorithm-insert sort

Source: Internet
Author: User

Hi, all, let's take a few minutes to write this insert sort algorithm down, the ideas is: definition a guard to store the original sorted array in this guard, assume the first num in the sorting data array is sorted, then guard loop to the end of this array, every
Per loop we will insert the new num to the sorted array and make the new array sorted, In the end the whole array is sorted, that's all.

The algorithm as follow:

 

/// <Summary> <br/> // insert sort method <br/> /// </Summary> <br/> /// <Param name = "Data "> original array </param> <br/> // <Param name =" count "> array length </param> <br/> Public void insertsort (INT [] data, int count) <br/>{< br/> // def the guard <br/> int temp; <br/> // assume the first num is sorted <br/> for (INT I = 1; I <count; I ++) <br/>{< br/> // stored the original sorted array in temp <br/> temp = data [I]; <br/> for (Int J = I; j> 0; j --) <br/> {<br/> // swap data [J] and data [J-1] <br/> If (temp <data [J-1]) <br/> {<br/> data [J] = data [J-1]; <br/> data [J-1] = temp; <br/>}< br/>}

 

And there is another algorithm as follow: This one is familiar with the up one.

 

 /// <Summary> <br/> // insert sort method 2 <br/> /// </Summary> <br/> // <Param name =" data "> original array </param> <br/> // <Param name =" count "> array length </param> <br/> Public void insertsort2 (INT [] data, int count) <br/>{< br/> // def the guard <br/> int temp, K = 0; <br/> // assume the first num is sorted <br/> for (INT I = 1; I <count; I ++) <br/> {<br/> // store the data [I]: Data [I] will be inserted to the sorted array <br/> temp = data [I]; <br/> K = 0; <br/> for (Int J = I; j> 0; j --) <br/> {<br/> If (temp <data [J-1]) <br/> {<br/> // move to behind <br/> data [J] = data [J-1]; <br/> // record the index j <br/> K = J; <br/>}< br/> // Insert the temp num <br/> If (k> 0) data [k-1] = temp; <br/>}< br/>}

 

Easy, simply.

Over.

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.