C + + implementation of direct insert sort (beginner version)
First, source code: InsertSortLow.cpp
1 /*Direct Insert sorting idea:2 Suppose that the records to be sorted are stored in the array R[1..N]. Initially, r[1] self into 1 ordered areas, unordered area is R[2..N]. 3 from i=2 up to i=n, sequentially insert r[i] into the current ordered area R[1..i-1], generating an ordered area with N Records. 4 */5 6#include <iostream>7 using namespacestd;8 /*functions that define the output of a one-dimensional array*/9 voidPrintintArray[],intN)Ten { One for(inti =0; I < n; i++) A { -cout << Array[i] <<" "; - } thecout <<Endl; - } - /* - first find the correct insertion position of r[i] in the current ordered area R[1..i-1] K (1≤k≤i-1); + then you will r[k. The records in I-1] move back one position, freeing up space on the K position to insert r[i]. - Note: + if r[i] has a keyword greater than or equal to r[1. I-1], then r[i] is inserted in the original position. A */ at intInsertsort (intArray[],intN) - { - //define variables, record interchange times - intCount =0; - //define intermediate variables as temporary swap variables - inttemp; in intJ; - //iterating through an array (sorting) tocout <<"begin sorting an array ..."<<Endl; + for(inti =1; I < n; i++) - { the //When the left element is greater than the right element * if(Array[i] < array[i-1]) $ {Panax Notoginseng //stores the current array element in a temporary variable -temp =Array[i]; the //moves the array elements from the I position (the element larger than the temp) back to the whole + for(j = i-1; J >=0&& array[j]>temp; j--) A { thecout <<"Section"<< (i +1) <<"Trip No."<< (j +1) <<"Second Order"<<Endl; + //moves the elements in an array back one unit after the whole -Array[j +1] =Array[j]; $cout << Array[j] <<"and the"<< Array[j +1] <<"swapped out"<<Endl; $ //output The order of the array at this time -cout <<"the order of the arrays at this time is:"; -Print (Array,Ten); the //Record Count plus 1 per Exchange -count++;Wuyi } theArray[j +1] =temp; - } Wu } -cout <<"array sort ended ..."<<Endl; About returncount; $ } - - intMain () - { A //define a one-dimensional array to sort + intArray[] = {1,3,4,5,2,6,Ten,9,8,7 }; the //Output Original Array -cout <<"the original array is:"<<Endl; $Print (Array,Ten); the //sorting an array the intCount = Insertsort (Array,Ten); the //output sorted Array thecout <<"the sorted array is:"<<Endl; -Print (Array,Ten); incout <<"co-Exchange"<< Count <<"Times"<<Endl; the return 0; the}
Second, the Operation effect
C + + implementation of direct insert sort (beginner version)