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.