Review data structure: Sorting (1) -- insert sorting and data structure sorting

Source: Internet
Author: User

Review data structure: Sorting (1) -- insert sorting and data structure sorting

Starting from this article, I began to review the knowledge points of the data structure. The blog mainly focuses on the core idea of each knowledge point and code implementation. This article begins with the insertion sorting in the sorting algorithm.


Stable sorting, inner sorting, suitable for sorting a small amount of data.
When the input array is sorted, the insertion sorting requires O (n) and the fast sorting requires O (n ^ 2 ).
When the input array is sorted in reverse order, the insertion order returns O (n ^ 2 ).
Average time complexity: O (n ^ 2 ).

Insert sorting: Insert a number into an array that has been arranged. by moving the position of this number, the inserted array is also ordered and repeat this process, in this way, all the 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 the element to be sorted, with the number of previous I-1 sorted {int j = I-1; // prepare advance 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 ;}






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.