The basic idea of a direct insert sort (insertion sort) is to insert a record to be sorted each time, by its keyword size, into the appropriate position in the previously ordered subsequence until all records have been inserted.
This algorithm is relatively simple, does not require too much explanation, the code is as follows:
1 /*2 * Insert the value which is at the index in data3 */4 voidInsert_sort (int*data,intIndexintvalue)5 {6 intTemp_index =index;7 for(inti =0; I < index;++i)8 {9 //find the first value that bigger than the passed valueTen if(Value <Data[i]) One { ATemp_index =i; - Break; - } the } - - inttemp =index; - while(Temp > Temp_index)//Right shift one number from the temp_index +Data[temp] = data[--temp]; -Data[temp_index] =value; +}
Here are the tests:
1 intMain ()2 {3 //int data[] = {3,2,6,1,30,-3};4 intData[] = {5,4,3,2,1,0};5 intLength =6;6 for(inti =1; I < length;++i)7 Insert_sort (Data,i,data[i]);8 9 for(inti =0; I < length;++i)Tencout << Data[i] <<" "; Onecout <<Endl; A return 0; -}
The results are as follows:
Insert sort of C + + implementation