Hand shake algorithm, hand shake Generator
How can we put the string upside down? We use the two pointers at the beginning and end of the string to scan the two sides in the middle, and constantly exchange the content of the two pointers,
void reverse(int a[], int n){ if(n < 2) return; for(int i = 0; i <= n;)swap(a[i++], a[--n]);}
Then, if you want to reverse the string, for example, if you want to replace the first n characters with the rest of the string, for example, n = 3, then the string changes to defgabc.
The handshaking algorithm is used here. The handshaking algorithm uses three-way inversion to reverse the string.
For abcdefg, n = 3, put the first n strings upside down, put the following strings upside down, and finally put the entire string upside down.
void rotation(int a[], int m, int n){ reverse(a, m); reverse(a+m, n-m); reverse(a, n);}
The complete code is as follows:
#include <iostream>using namespace std;void reverse(int a[], int n){ if(n < 2) return; for(int i = 0; i <= n;) swap(a[i++], a[--n]);}void rotation(int a[], int m, int n){ reverse(a, m); reverse(a+m, n-m); reverse(a, n);}int main(){ int a[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}; int n = sizeof(a) / sizeof(int); rotation(a, 7, n); for(int i = 0; i < n; ) cout << a[i++] << " "; return 0;}
The spatial complexity of insert and Merge Sorting is O (n). If you use the hand shake algorithm to merge in situ, the spatial complexity is O (1 ).