Insert sort directly

Source: Internet
Author: User
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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.