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

Source: Internet
Author: User


From this beginning, plan to review the basic knowledge of data structure. One is to find a job after a year, and the other is to improve their programming skills. Since these data structure knowledge points have been learned before, here we refine the core of each knowledge point, as well as the code implementation.


This first says the insertion sort in the sorting algorithm.


Insertion Sorting is a sort of stable sorting algorithm, which belongs to the ordering of the inner sort, 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 code is implemented 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 algorithm (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.