Jon Bentley in Programming Pearls Column 2 describes what has came to be known as the most elegant, efficient solution.
The rotation algorithm uses a function
reverse()
that reverses subsequences of the array. Quoting from the column:Let's view the problem as transforming the array
ab
into the arrayba
, but let's also assume that we have a function that reverses the elements in a specified portion of the array. Starting with ab, we reverse a to get a_r b, reverse b to get a_r b_r, and then reverse the whole thing to get (a_r b_r)_r, which is exactly ba.
This is what you need. The input from the user defines the place where you will partition the array into two blocks A and B. Here's my implementation:
void reverse(int a[], int sz) {
int i, j;
for (i = 0, j = sz; i < j; i++, j--) {
int tmp = a[i];
a[i] = a[j];
a[j] = tmp;
}
}
void rotate(int array[], int size, int amt) {
if (amt < 0)
amt = size + amt;
reverse(array, size-amt-1);
reverse(array+size-amt, amt-1);
reverse(array, size-1);
}
I tested it and it's working. Also, note how negative rotations are handled: rotating an array of size
elements amt
to the left (i.e. with negative values) is the same as rotating it size+amt
to the right.
Enjoy the elegant code, and don't forget to include credits in a comment (to Jon Bentley, of course).
-------------------For right rotate use:
temp[0]=a[0];
for(i=1;i<=n;i++)
{
temp[i%2]=a[(i*d)%n];
a[(i*d)%n]=temp[(i+1)%2];
}
For left rotate use:
temp[0]=a[0];
for(i=1;i<=n;i++)
{
temp[i%2]=a[(i*(n-d))%n];
a[(i*(n-d))%n]=temp[(i+1)%2];
}
여기서 a [n]은 배열이고 d는 회전하려는 위치의 수입니다.
-------------------요소 위치를 바꾸는 것입니다. 위치 1의 요소는 위치 6에 배치되고 그 반대의 경우도 마찬가지입니다. 마지막 부분을 다시 작성해야합니다. 두 가지 방법이 있습니다.
- 새 배열을 할당하고 값을 하나씩 복사하십시오.
- 하나의 값을 tmp에 저장하고 다른 값을 이동하십시오.
사소한 접근 방식은 회전하는 것이지만 그 이상을 살펴보면 배열 / 목록의 요소 위치를 변경하는 것은 어떨까요?
def circularArrayRotation(a, k):
k=k%len(a)
b=a[len(a)-k:len(a)]
#print(b)
a=b+a[0:len(a)-k]
print(a)
그건 오른쪽 회전, 왼쪽 회전은 그냥 뒤집기
b=a[k:len(a)] and a=b+a[0:k]
출처
https://stackoverflow.com/questions/22079831