Insert sorting is very simple, just like playing poker. There is a card 4 in your hand, and another card 5 will be put to the right of the first card. If 3 is displayed, scan from right to left. If the left side is larger than the number to be inserted, it is switched.
Insert sorting is a stable sorting method, with time complexity O (N * n) and space complexity O (1). In the best case, the time complexity is O (1 ). that is, if it is an ordered or equal array, it only needs to be compared n-1 times. Below is the source code, just three lines of code.
// ================================================ ==================================================================== // Name: quiksort. CPP // Author: Yanzi // version: // copyright: Your copyright notice // Description: Hello world in C ++, ANSI-style // ========================================== ========================================================== = # include <iostream> # include <malloc. h> using namespace STD; void swap1 (int A, int B); void printarray (int * In, int N); void quicksort1 (int * X, int l, int R); // bilateral scan, quick sorting void quicksort2 (int x [], int L, int R); // unilateral scan, quick sorting void swap2 (Int &, int & B); // exchange, this method must be used on mingw, swap1 is invalid # define N 8 // The length of the array int main () {int * input = NULL; input = (int *) malloc (N * sizeof (INT); If (input = NULL) {cout <"memory overflow" <Endl ;} for (INT I = 0; I <n; I ++) {input [I] = rand ();} // int input [] = {55, 41, 59, 26, 53, 58, 97, 93}; cout <"Raw data:" <Endl; printarray (input, n); quicksort2 (input, 0, N-1 ); printarray (input, n); Return 0;} void swap1 (int A, int B) {int temp = A; A = B; B = temp ;} void printarray (int * In, int N) {If (in = NULL) {return;} For (INT I = 0; I <n; I ++) {cout <"" <in [I];} cout <Endl;} void quicksort1 (int * X, int L, int R) {If (L <R) {int I = L, j = r, key = x [l]; while (I <j) {While (I <J & X [J]> = key) {J --;} if (I <j) {x [I ++] = x [J];} while (I <J & X [I] <= key) {I ++;} if (I <j) {x [j --] = x [I] ;}} cout <"I =" <I <"J =" <j <Endl; X [I] = key; quicksort1 (x, L, I-1 ); quicksort1 (x, I + 1, R) ;}} void quicksort2 (INT X [], int L, int R) {If (L> = r) return; int M = L; for (INT I = L + L; I <= r; I ++) {If (X [I] <X [l]) {swap2 (X [++ m], X [I]) ;}} swap2 (X [L], X [m]); quicksort2 (x, l, m-1); quicksort2 (x, m + 1, R);} void swap2 (Int & A, Int & B) {if (a = B) return; // for data exchange at the same address, the result will be 0a = a ^ B; B = a ^ B; A = a ^ B ;}
A major feature of insert sorting: It is very suitable for a basic ordered array for exact sorting.