Array Element looping left/right shifting

Source: Internet
Author: User
The Assembly Language and C language both have cyclic shift instructions or operators, which can be used to shift the loop left or right several bits. However, to move several elements left or right in an array, but cannot be directly implemented. The following uses the circular left shift of character arrays as an example to discuss solutions to these problems. For the character array s [8] = "abcdefg", the loop shifts M = 3 places to "defgabc", and write the function implementation. Analysis: There are two methods that are most likely to come to mind:
  1. Apply for a 3-byte space, copy "ABC", move the remaining characters from left to right to the corresponding position, and finally copy "ABC" to the end, space is released and the algorithm ends. In this way, the time complexity is O (n), and the space complexity is O (m ).
  2. Only one byte of auxiliary space is used. Each time the string loop is shifted by one character to the left, m times in total. In this way, the time complexity is O (m · N) and the space complexity is O (1 ).

Although the above two methods are simple, the time (or space) complexity is unsatisfactory. Is there an algorithm with the time complexity O (N) and the space complexity O (1? Next, let's look at it.

Solution 1

Set the string length to N and the temporary variable to T. The algorithm is as follows:

  1. Set I = 0
  2. J = I, save s [J] to T
  3. Shift s [(j + n) % m] Forward N bits to the final position s [J % m]
  4. J + = N
  5. If J % m! = I, go to 3; otherwise, go to the next step.
  6. I ++
  7. If I <gcd (m, n), it is converted to 2; otherwise, the algorithm ends after moving.

The implementation code is as follows:

/*************************************** ***************************
* Copyright (c) 2005-2007 CUG-CS
* All Rights Reserved
*
* File name: stringshift. c
* Brief Description: shifts the left of a string loop.
*
* Version: 1.0
* Author: raincatss
* Completion date: 2007-11-18
* Development Environment: Windows XP SP2 + vc6.0
* Blog: http://raincatss.cublog.cn/
**************************************** **************************/

#include <stdio.h>
#include <string.h>
#include <assert.h>

static int gcd(int m, int n);

void StringShift(char *str, int n)
{
    int i, j, len;
    char tmp;

    assert(NULL != str);
    len = strlen(str);
    if (n <= 0 || n >= len) {
        return;
    }
    
    for (i = 0; i < gcd(len, n); i++) {
        j = i;
        tmp = str[j];
        do {
            str[j] = str[(j + n) % len];
            j = (j + n) % len;
        } while (j != i);
        str[(j + len - n) % len] = tmp;
    }
}

static int gcd(int m, int n)
{
    int tmp;

    while (n != 0) {
        tmp = m % n;
        m = n;
        n = tmp;
    }

    return m;
}

In the do {} while () loop, if K does not modulo with Len after N is added each time, we can find that K-I is equal to the minimum public multiple of M and N, this ensures that there are no repeated subscripts in the loop process (why? Think for yourself ). The reason for making the for () loop gcd (m, n) times is that every do {} while () loop does M * n/(n * gcd (m, n )) = m/gcd (m, n) times. The for () loop performs gcd (m, n) times to ensure that all elements are moved once. (If anyone has the exact and clear mathematical proof of this method, please email: raincatss # gmail.com)

Solution 2

Divide the original string into three parts: ablbr (the same length as a), move the loop left, and then enter blbra. You can first change the interchange position between A and BR into brbla, and then swap the BR with BL, so that recursive solutions can be obtained.

The Recursive Implementation Code is as follows:

/*************************************** ***************************
* Copyright (c) 2005-2007 CUG-CS
* All Rights Reserved
*
* File name: stringshift. c
* Brief Description: shifts the left of a string loop.
*
* Version: 1.0
* Author: raincatss
* Completion date: 2007-11-18
* Development Environment: Windows XP SP2 + vc6.0
* Blog: http://raincatss.cublog.cn/
**************************************** **************************/

#include <stdio.h>
#include <assert.h>

static void Swap(char *p, char *q);

void StringShift(char *str, int len, int n)
{
    int i;

    assert(NULL != str);
    if (len <= 0 || n <= 0 || n >= len) {
        return;
    }

    if (n < len - n) {
        for (i=0; i<n; i++) {
            Swap(&str[i], &str[len - n + i]);
        }
        StringShift(str, len - n, n);
    } else if (n > len - n) {
        for (i=len-1; i>n-1; i--) {
            Swap(&str[i], &str[i - n]);
        }
        StringShift(str + len - n, n, n + n - len);
    } else {
        for (i=0; i<n; i++) {
            Swap(&str[i], &str[n + i]);
        }
    }
}

static void Swap(char *p, char *q)
{
    char tmp = *p;
    *p = *q;
    *q = tmp;
}

To improve efficiency, you can convert Recursion TO iteration. The implementation code is as follows:

/*************************************** ***************************
* Copyright (c) 2005-2007 CUG-CS
* All Rights Reserved
*
* File name: stringshift. c
* Brief Description: shifts the left of a string loop.
*
* Version: 1.0
* Author: raincatss
* Completion date: 2007-11-18
* Development Environment: Windows XP SP2 + vc6.0
* Blog: http://raincatss.cublog.cn/
**************************************** **************************/

#include <stdio.h>
#include <assert.h>

static void Swap(char *p, char *q);

void StringShift(char *str, int len, int n)
{
    int i, tmp;
    char *s = str;

    assert(NULL != str);
    if (len <= 0 || n <= 0 || n >= len) {
        return;
    }

    while (n != len - n) {
        if (n < len - n) {
            for (i=0; i<n; i++) {
                Swap(&s[i], &s[len - n + i]);
            }
            len -=n;
        } else {
            for (i=len-1; i>n-1; i--) {
                Swap(&s[i], &s[i - n]);
            }
            s += len - n;
            tmp = n;
            n = n + n - len;
            len = tmp;
        }
    }
    for (i=0; i<n; i++) {
        Swap(&s[i], &s[n + i]);
    }
}

static void Swap(char *p, char *q)
{
    char tmp = *p;
    *p = *q;
    *q = tmp;
}

Solution 3

First, the first n characters are sorted in reverse order, then the last M-n characters are sorted in reverse order, and then the final result is obtained.

The code is implemented as follows:

/*************************************** ***************************
* Copyright (c) 2005-2007 CUG-CS
* All Rights Reserved
*
* File name: stringshift. c
* Brief Description: shifts the left of a string loop.
*
* Version: 1.0
* Author: raincatss
* Completion date: 2007-11-18
* Development Environment: Windows XP SP2 + vc6.0
* Blog: http://raincatss.cublog.cn/
**************************************** **************************/

#include <string.h>
#include <assert.h>

static void Swap(char *p, char *q);
static void Reverse(char *str, int i, int n);

void String_Shift_Reverse(char *str, int n)
{
    int len;
    
    assert(NULL != str);
    len = strlen(str);
    if (n <=0 || n >= len) {
        return;
    }

    Reverse(str, 0, n - 1);
    Reverse(str, n, len - 1);
    Reverse(str, 0, len - 1);
}

static void Swap(char *p, char *q)
{
    char tmp;

    tmp = *p;
    *p = *q;
    *q = tmp;
}

static void Reverse(char *str, int i, int n)
{
    int l, r;

    for (l = i, r = n; l < r; l++, r--) {
        Swap(&str[l], &str[r]);
    }
}

 

To sum up, solution 3 is simple and recommended.

Reference: Jon Bentley, "programming pearls (second edition)", Beijing: People's post and telecommunications Press, 2007

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.