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