60 数组内交换头尾;61打乱顺序
package com.fqs.test; import java.util.Arrays; public class hello { public static void main(String[] args) { //交换数组头尾交换 //交换前 12345 //交换后 54321 int []arr={1,2,3,4,5}; int temp=arr[0]; for (int i = 0,j=arr.length-1; i <=j/2 ; i++,j--) { temp=arr[i]; arr[i]=arr[j]; arr[j]=temp; } System.out.println("交换后的数组:"+Arrays.toString(arr)); } }
打乱顺序
package com.fqs.test; import java.util.Arrays; import java.util.Random; public class hello { public static void main(String[] args) { //打乱数组中的顺序 int []arr={1,2,3,4,5}; Random r=new Random(); int temp=arr[0]; for (int i = 0; i <arr.length ; i++) { //随机下标和i下标交换 int r_num=r.nextInt(5); System.out.println("随机数r_num:"+r_num); temp=arr[i]; arr[i]=arr[r_num]; arr[r_num]=temp; } System.out.println(Arrays.toString(arr)); } }