在java中,手写实现一个数字的首位交换算法实现
实现效果
实现代码
- 核心业务代码
public static void main(String[] args) {
int[] arr = {1,2,3,4,5};
int temp = arr[0];
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
System.out.println("");
for (int i = 0,j = arr.length-1; i < j; i++,j--) {
temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}
- 随机打乱数组
public static void main(String[] args) {
// 打乱数组的顺序
int[] arr = {1,2,3,4,5};
// 获取随机索引
Random random = new Random();
for (int i = 0; i < arr.length; i++) {
int index = random.nextInt(arr.length);
int temp = arr[i];
arr[i] = arr[index];
arr[index] = temp;
}
for (int i = 0; i < arr.length; i++) {
System.out.print(arr[i]);
}
}