package com.ming.scanner;
import java.util.Scanner;
public class Demo1_Sacnner {
public static void main(String[] args) {
int [] arr1 ={10,20,30,40,50,60,70,80,90,100,110,120,130,140,150,160,170};
System.out.println("未左移时数组");
System.out.println("----------------------------------");
for (int i = 0; i <arr1.length; i++) {
System.out.print(arr1[i]+" ");
}
System.out.println();
//开始左移
Scanner sc=new Scanner(System.in);
System.out.println("请输入左移位数");
int p=sc.nextInt();
Demo1_Sacnner.LeftRun(arr1,p,arr1.length);
System.out.println("左移后数组");
System.out.println("----------------------------------");
for (int i = 0; i <arr1.length; i++) {
System.out.print(arr1[i]+" ");
}
}
public static void LeftRun(int arr[],int p/*左移多少位**/,int n/*数组长度*/){
if(n<0||p>n){
System.out.println("输入有误");
}else{
//p%=n; 右移模除
Reverse(arr,0,p-1);//右移: 0 到 n-p-1
Reverse(arr,p,n-1);//右移:n-p 到 n-1
Reverse(arr,0,n-1);
}
}
public static void Reverse(int arr[],int Strat/*开始处*/,int End/*结束处*/){
int j,i;
int temp;
for(i=Strat,j=End;i<j;i++,j--) {
temp=arr[i];
arr[i]=arr[j];
arr[j]=temp;
}
}
}
数组的左循环移动和右循环移动
最新推荐文章于 2022-11-17 10:12:50 发布