To insert a sort definition directly:
each time the first element is taken out of the unordered table, it is inserted into the proper position of the ordered table so that the ordered table remains orderly. The direct insert sort is a stable sort, the worst time complexity is O (n^2), and the spatial complexity is O (1).
classprogram{Static voidMain (string[] args) { int[] Array =New[] {234,632, at,643,2,6, -2,423,2342, + }; Console.WriteLine ("before sorting:"); Console.WriteLine (string. Join (",", array)); Insertsort (array); Console.WriteLine ("after sorting:"); Console.WriteLine (string. Join (",", array)); Console.readkey (); } /// <summary> ///Direct Insert Sort/// </summary> /// <param name= "Sources" >Target Array</param> Private Static voidInsertsort (int[] sources) { //starting at index 1, suppose Sources[0] is ordered for(inti =1, Len = sources. Length-1; I <= Len; i++) { //prepare the data to be inserted intInsertvalue =Sources[i],//Suppose you want to insert an indexInsertindex = i-1; //traverse the index where the lookup is inserted while(Insertindex >=0&& Insertvalue <Sources[insertindex]) { //move the current data back oneSources[insertindex +1] =Sources[insertindex]; Insertindex--; } //do not meet the above conditions, indicating location, insert dataSources[insertindex +1] =Insertvalue; } } /// <summary> ///Direct Insert sort for implementation/// </summary> /// <param name= "Sources" >Target Array</param> Private Static voidInsertSort1 (int[] sources) { for(inti =1, Len = sources. Length-1; I <= Len; i++) { for(intj = i; J >0; j--) { if(Sources[j] > Sources[j-1])//> Descending, < ascending { inttemp =Sources[j]; SOURCES[J]= Sources[j-1]; Sources[j-1] =temp; } } } }}
Direct insertion sort of sorting algorithm