背景:
解决办法
import java.util.Arrays;
/**
* Description:
* user:james
* Date:2022-10-15
* Time:20:14
*/
public class Test {
public static void main(String[] args) {
int [] result = {1,2,3,4,5,6,7};
// long startTime = System.nanoTime();
// System.out.println(Arrays.toString(result));
// leftExchange(result,4,7);
// System.out.println(Arrays.toString(result));
// long endTime = System.nanoTime();
// System.out.println(endTime-startTime);
leftExchange(result,2,7);
System.out.println(Arrays.toString(result));
int [] result1 = {1,2,3,4,5,6,7};
rightExchange(result1,2,7);
System.out.println(Arrays.toString(result1));
}
//逆置算法
public static void Reserve(int temp[] , int left , int right){
int mid = (left+right)/2;
for(int i=0;i<=mid-left;i++){
int result=temp[left+i];
temp[left+i]=temp[right-i];
temp[right-i]=result;
}
}
//循环左移
public static void leftExchange(int temp[],int p,int n){ //p:移动单位 n:数组长度
Reserve(temp,0,p-1);//逆置前p个
Reserve(temp,p,n-1);//逆置后n-p个
Reserve(temp,0,n-1);//逆置整个数组
}
//循环右移
public static void rightExchange(int temp[],int p ,int n){
Reserve(temp,0,n-1); //逆置整个数组
Reserve(temp,0,p-1);//逆置前p个
Reserve(temp,p,n-1);//逆置后n-p个
}
}
总结:
循环右移:
先逆置整个数组,再逆置前p个,最后逆置后n-p个;
例如:{1,2,3,4,5,6} 循环右移( p=2 )个单位
循环左移:
先逆置前p个,再逆置后n-p个,再逆置整个数组;
例如:{1,2,3,4,5,6}循环左移( p=2 )个单位