📜  将数组循环旋转 1 的程序

📅  最后修改于: 2022-05-13 01:57:51.775000             🧑  作者: Mango

将数组循环旋转 1 的程序

给定一个数组,将数组顺时针循环旋转一圈。

例子:

Input:  arr[] = {1, 2, 3, 4, 5}
Output: arr[] = {5, 1, 2, 3, 4}

以下是步骤。
1) 将最后一个元素存储在变量 x 中。
2) 将所有元素向前移动一位。
3) 用 x 替换数组的第一个元素。

C++
// C++ code for program
// to cyclically rotate
// an array by one
# include 
using namespace std;
 
void rotate(int arr[], int n)
{
    int x = arr[n - 1], i;
    for (i = n - 1; i > 0; i--)
    arr[i] = arr[i - 1];
    arr[0] = x;
}
 
// Driver code
int main()
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr) /
            sizeof(arr[0]);
 
    cout << "Given array is \n";
    for (i = 0; i < n; i++)
        cout << arr[i] << ' ';
 
    rotate(arr, n);
 
    cout << "\nRotated array is\n";
    for (i = 0; i < n; i++)
        cout << arr[i] << ' ';
 
    return 0;
}
 
// This code is contributed by jit_t


C
#include 
 
void rotate(int arr[], int n)
{
   int x = arr[n-1], i;
   for (i = n-1; i > 0; i--)
      arr[i] = arr[i-1];
   arr[0] = x;
}
 
int main()
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr)/sizeof(arr[0]);
 
    printf("Given array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
 
    rotate(arr, n);
 
    printf("\nRotated array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
 
    return 0;
}


Java
import java.util.Arrays;
 
public class Test
{
    static int arr[] = new int[]{1, 2, 3, 4, 5};
     
    // Method for rotation
    static void rotate()
    {
       int x = arr[arr.length-1], i;
       for (i = arr.length-1; i > 0; i--)
          arr[i] = arr[i-1];
       arr[0] = x;
    }
     
    /* Driver program */
    public static void main(String[] args)
    {
        System.out.println("Given Array is");
        System.out.println(Arrays.toString(arr));
         
        rotate();
         
        System.out.println("Rotated Array is");
        System.out.println(Arrays.toString(arr));
    }
}


Python3
# Python3 code for program to
# cyclically rotate an array by one
 
# Method for rotation
def rotate(arr, n):
    x = arr[n - 1]
     
    for i in range(n - 1, 0, -1):
        arr[i] = arr[i - 1];
         
    arr[0] = x;
 
 
# Driver function
arr= [1, 2, 3, 4, 5]
n = len(arr)
print ("Given array is")
for i in range(0, n):
    print (arr[i], end = ' ')
 
rotate(arr, n)
 
print ("\nRotated array is")
for i in range(0, n):
    print (arr[i], end = ' ')
 
# This article is contributed
# by saloni1297


C#
// C# code for program to cyclically
// rotate an array by one
using System;
 
public class Test
{
    static int []arr = new int[]{1, 2, 3, 4, 5};
     
    // Method for rotation
    static void rotate()
    {
    int x = arr[arr.Length - 1], i;
     
    for (i = arr.Length - 1; i > 0; i--)
        arr[i] = arr[i-1];
    arr[0] = x;
    }
     
    // Driver Code
    public static void Main()
    {
        Console.WriteLine("Given Array is");
        string Original_array = string.Join(" ", arr);
        Console.WriteLine(Original_array);
          
        rotate();
         
        Console.WriteLine("Rotated Array is");
        string Rotated_array = string.Join(" ", arr);
        Console.WriteLine(Rotated_array);
    }
}
 
// This code is contributed by vt_m.


PHP
 0; $i--)
    $arr[$i] = $arr[$i - 1];
    $arr[0] = $x;
}
 
// Driver code
$arr = array(1, 2, 3, 4, 5);
$n = sizeof($arr);
 
echo "Given array is \n";
for ($i = 0; $i < $n; $i++)
    echo $arr[$i] . " ";
 
rotate($arr, $n);
 
echo "\nRotated array is\n";
for ($i = 0; $i < $n; $i++)
    echo $arr[$i] . " ";
 
// This code is contributed
// by ChitraNayal
?>


Javascript


C++
#include 
using namespace std;
 
void rotate(int arr[], int n)
{
    int i = 0, j = n-1; // i and j pointing to first and last element respectively
      while(i != j){
      swap(arr[i], arr[j]);
      i++;
    }
}
 
// Driver code
int main()
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr) /
            sizeof(arr[0]);
 
    cout << "Given array is \n";
    for (i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    rotate(arr, n);
 
    cout << "\nRotated array is\n";
    for (i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    return 0;
}


C
#include 
 
void swap(int *x, int *y)
{
  int temp = *x;
  *x = *y;
  *y = temp;
}
void rotate(int arr[], int n)
{
  int i = 0, j = n - 1;
  while(i != j)
  {
    swap(&arr[i], &arr[j]);
    i++;
  }
}
 
int main()
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr)/sizeof(arr[0]);
 
    printf("Given array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
 
    rotate(arr, n);
 
    printf("\nRotated array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
 
    return 0;
}


Java
import java.util.Arrays;
 
public class Test
{
    static int arr[] = new int[]{1, 2, 3, 4, 5};
     
    
    static void rotate()
    {
       int i = 0, j = arr.length - 1;
       while(i != j)
       {
         int temp = arr[i];
         arr[i] = arr[j];
         arr[j] = temp;
         i++;
       }
    }
     
    /* Driver program */
    public static void main(String[] args)
    {
        System.out.println("Given Array is");
        System.out.println(Arrays.toString(arr));
         
        rotate();
         
        System.out.println("Rotated Array is");
        System.out.println(Arrays.toString(arr));
    }
}


Python3
def rotate(arr, n):
    i = 0
    j = n - 1
    while i != j:
      arr[i], arr[j] = arr[j], arr[i]
      i = i + 1
    pass
 
 
# Driver function
arr= [1, 2, 3, 4, 5]
n = len(arr)
print ("Given array is")
for i in range(0, n):
    print (arr[i], end = ' ')
 
rotate(arr, n)
 
print ("\nRotated array is")
for i in range(0, n):
    print (arr[i], end = ' ')


C#
// C# code for program to cyclically
// rotate an array by one
using System;
 
class GFG{
     
static int []arr = new int[]{ 1, 2, 3, 4, 5 };
 
// Method for rotation
static void rotate()
{
    int n = arr[arr.Length - 1];
     
    // i and j pointing to first and
    // last element respectively
    int i = 0, j = n - 1;
    while(i != j)
    {
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    i++;
    }
}
 
// Driver Code
public static void Main()
{
    Console.WriteLine("Given Array is");
    string Original_array = string.Join(" ", arr);
    Console.WriteLine(Original_array);
      
    rotate();
     
    Console.WriteLine("Rotated Array is");
    string Rotated_array = string.Join(" ", arr);
    Console.WriteLine(Rotated_array);
}
}
 
// This code is contributed by annianni


Javascript


Python3
def rotateArray(array):
    '''
    array[-1:] taking last element
    array[:-1] taking elements from start to last second element
    array[:] changing array from starting to end
    '''
    array[:] = array[-1:]+array[:-1]
 
 
# create array
array = [1, 2, 3, 4, 5]
# send array to rotateArray function
rotateArray(array)
 
print(*array)  # 5 1 2 3 4


输出
Given array is 
1 2 3 4 5 

Rotated array is
5 1 2 3 4 

时间复杂度:O(n) 因为我们需要遍历所有元素
辅助空间:O(1)
上述问题也可以通过反转算法来解决。

另一种方法:

我们可以使用两个指针,比如ij ,它们分别指向数组的第一个最后一个元素。正如我们在循环旋转中所知道的,我们会将最后一个元素放在第一个元素并向前移动其余元素,因此开始交换 arr[i] 和 arr[j] 并保持 j 固定并且 i 向 j 移动。重复直到 i 不等于 j。

C++

#include 
using namespace std;
 
void rotate(int arr[], int n)
{
    int i = 0, j = n-1; // i and j pointing to first and last element respectively
      while(i != j){
      swap(arr[i], arr[j]);
      i++;
    }
}
 
// Driver code
int main()
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr) /
            sizeof(arr[0]);
 
    cout << "Given array is \n";
    for (i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    rotate(arr, n);
 
    cout << "\nRotated array is\n";
    for (i = 0; i < n; i++)
        cout << arr[i] << " ";
 
    return 0;
}

C

#include 
 
void swap(int *x, int *y)
{
  int temp = *x;
  *x = *y;
  *y = temp;
}
void rotate(int arr[], int n)
{
  int i = 0, j = n - 1;
  while(i != j)
  {
    swap(&arr[i], &arr[j]);
    i++;
  }
}
 
int main()
{
    int arr[] = {1, 2, 3, 4, 5}, i;
    int n = sizeof(arr)/sizeof(arr[0]);
 
    printf("Given array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
 
    rotate(arr, n);
 
    printf("\nRotated array is\n");
    for (i = 0; i < n; i++)
        printf("%d ", arr[i]);
 
    return 0;
}

Java

import java.util.Arrays;
 
public class Test
{
    static int arr[] = new int[]{1, 2, 3, 4, 5};
     
    
    static void rotate()
    {
       int i = 0, j = arr.length - 1;
       while(i != j)
       {
         int temp = arr[i];
         arr[i] = arr[j];
         arr[j] = temp;
         i++;
       }
    }
     
    /* Driver program */
    public static void main(String[] args)
    {
        System.out.println("Given Array is");
        System.out.println(Arrays.toString(arr));
         
        rotate();
         
        System.out.println("Rotated Array is");
        System.out.println(Arrays.toString(arr));
    }
}

Python3

def rotate(arr, n):
    i = 0
    j = n - 1
    while i != j:
      arr[i], arr[j] = arr[j], arr[i]
      i = i + 1
    pass
 
 
# Driver function
arr= [1, 2, 3, 4, 5]
n = len(arr)
print ("Given array is")
for i in range(0, n):
    print (arr[i], end = ' ')
 
rotate(arr, n)
 
print ("\nRotated array is")
for i in range(0, n):
    print (arr[i], end = ' ')

C#

// C# code for program to cyclically
// rotate an array by one
using System;
 
class GFG{
     
static int []arr = new int[]{ 1, 2, 3, 4, 5 };
 
// Method for rotation
static void rotate()
{
    int n = arr[arr.Length - 1];
     
    // i and j pointing to first and
    // last element respectively
    int i = 0, j = n - 1;
    while(i != j)
    {
        {
            int temp = arr[i];
            arr[i] = arr[j];
            arr[j] = temp;
        }
    i++;
    }
}
 
// Driver Code
public static void Main()
{
    Console.WriteLine("Given Array is");
    string Original_array = string.Join(" ", arr);
    Console.WriteLine(Original_array);
      
    rotate();
     
    Console.WriteLine("Rotated Array is");
    string Rotated_array = string.Join(" ", arr);
    Console.WriteLine(Rotated_array);
}
}
 
// This code is contributed by annianni

Javascript


输出
Given array is 
1 2 3 4 5 
Rotated array is
5 1 2 3 4 

另一种方法(使用切片):

我们也可以在Python中使用切片来解决这个问题。

上述方法的实施:-

Python3

def rotateArray(array):
    '''
    array[-1:] taking last element
    array[:-1] taking elements from start to last second element
    array[:] changing array from starting to end
    '''
    array[:] = array[-1:]+array[:-1]
 
 
# create array
array = [1, 2, 3, 4, 5]
# send array to rotateArray function
rotateArray(array)
 
print(*array)  # 5 1 2 3 4
输出
5 1 2 3 4