Code Using System;
Using System. Collections. Generic;
Public class MyClass
{
Public static void Main ()
{
Int [] data = {2, 8, 4, 1, 6, 3, 7, 9, 5 };
Insertsort (data );
Console. ReadLine ();
}
Public static void Insertsort (int [] data)
{
For (int I = 1; I <data. Length; I ++)
{
Int temp = data [I];
Int j = 0;
For (j = I-1; j> = 0 & temp <data [j]; j --)
{
Data [j + 1] = data [j];
}
Data [j + 1] = temp;
}
For (int I = 0; I <data. Length; I ++)
{
Console. WriteLine (data [I]. ToString ());
}
}
}
The time complexity of directly inserting sorting algorithms is divided into three situations: the best, the worst, and the random:
(1) The best case is that all records in the sequence table are sorted in order. At this time, the number of Outer Loops is n-1, and the number of inner loops is 0. In this way, the number of comparisons per record in the outer loop is 1, so the time complexity of directly inserting the Sorting Algorithm is O (n) in the best case ).
(2) The worst case is that records in the sequence table are in reverse order. At this time, the cycle coefficient of the inner loop is I each time. In this way, the number of comparisons for the entire outer loop is
Therefore, the time complexity of directly inserting a sorting algorithm in the worst case is O (n2 ).
(3) If the records in the sequence table are arranged randomly, the expected number of comparisons is n2/4. Therefore, the time complexity of directly inserting a sorting algorithm is O (n2 ).
It can be proved that the more records in the sequence table are close to the order, the higher the efficiency of directly inserting the sorting algorithm, and the time efficiency is between O (n) to O (n2.
The space complexity of directly inserting the Sorting Algorithm is O (1 ). Therefore, direct insertion of sorting algorithms is a stable sorting algorithm.