Sort-Insert Method

Source: Internet
Author: User

Basic idea:

Inserts elements into an ordered sequence.

Sorting process: The entire sort process is n-1, that is, the first record in the sequence is considered an ordered subsequence, and then the 2nd record begins, one by one, until the entire sequence is ordered.

Essence: Perform n-1 operations on the linear table, but first find the insertion position.

V[0], v[1], ..., v[i-1] already in order. At this time, with V[i] keywords and v[i-1], v[i-2], ... To find the insertion position near V[i]] insert, and the object in the original position moves backwards.
Insert sort key: 1, take out an element, leave the position, 2 the element that matches the condition moves back.

Time complexity O (n^2)


Example code:

#include <iostream> #include <cstdio> #include <ctime> #include <iomanip>using namespace std; int arr[10000];void Insertsrot (int *a, int len) {for (int i = 1; i < Len; i++) {int k = i;//insert position int tmp = Arr[k];for (int j = i-1; J >= 0 && arr[j] > tmp; j--) {arr[j + 1] = arr[j];//element shift k = j;} ARR[K] = tmp; Element Insert}}void printArray (int *a, int len) {for (int i = 0; i < len; i++) {if (I! = 0 && I% = = 0) {cout <& Lt Endl;} cout << SETW (3) << a[i] << ';} cout << Endl;} int main () {Srand (time (0)); cout << "Please input length of array:"; int len;cin >> len;for (int i = 0; i < Len; i++) {Arr[i] = rand ()% 100;} cout << "before sorting:\n";p Rintarray (arr, Len), Insertsrot (arr, Len), cout << "after sorting:\n"; PrintArray (arr, Len); return 0;}  /*please input length of Array:20before sorting:41 5 45 17 35 58 29 61 98 8927 8 97 83 89 3 25 59 12  44After Sorting:3 5 8 12 1725 27 29 35 4144 45 58 59 61 83 89 89 97 98*/ 




Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Sort-Insert Method

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.