Review data structure: sort (i)--insert Sort

Source: Internet
Author: User

From this beginning, I began to review the data structure of the knowledge point, the blog is mainly focused on each knowledge point of the core ideas, as well as code implementation. This first begins with the insertion sort in the sorting algorithm.


Stable sorting, sorting within, suitable for a small amount of data.
When the input array is already sorted, an O (n) is required for the insertion Order, and O (n^2) is required for the fast line.
When the input array is sorted in reverse order, the insertion sort is complex: O (n^2).
Average time complexity: O (n^2).

The basic procedure for inserting a sort is to insert a number into an array that is already arranged, by moving the number of positions, so that the inserted array is also ordered, repeating the process so that all the final numbers are ordered.


The implementation code is as follows:

#include <iostream>using namespace std; void Insertsort (int a[], int n) {for (int i = 1; i < n; i++) {if (A[i] < a[i-1])  //A[i] is a pending element, the preceding i-1 number is sorted {int J = i -1;  Prepare to move forward int x = a[i]; A[i] = a[i-1]; while (x < a[j]) {a[j+1] = a[j]; j--;} A[J+1] = x; }}}int Main () {int a[] = {2, 1, 5, 8, 4, 3}; Insertsort (A, 6); for (int i = 0; i< 6; i++) cout<<a[i]<< "; cout<<endl; return 0; }






Review data structure: sort (i)--insert Sort

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.