Hand shake algorithm, hand shake Generator

Source: Internet
Author: User

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 ).

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.