通过反转所需大小的子数组,可以按给定大小的组反转数组。一个例子如下。
Array = 1 2 3 4 5 6 7 8 9 10 Group size = 3 Modified array = 3 2 1 6 5 4 9 8 7 10
演示此过程的程序如下。
public class Example { public static void main(String[] args) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9 ,10}; int size = 4; int n = arr.length; System.out.print("Original array is: "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); for (int i = 0; i < n; i += size) { int left = i; int right = Math.min(i + size - 1, n - 1); int temp; while (left < right) { temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left += 1; right -= 1; } } System.out.print("\nModified array is: "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); } }
输出结果
Original array is: 1 2 3 4 5 6 7 8 9 10 Modified array is: 4 3 2 1 8 7 6 5 10 9
现在让我们了解上面的程序。
首先打印原始数组。然后,使用for循环将给定大小(即4)的组反转为数组。演示此操作的代码段如下所示。
System.out.print("Original array is: "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " "); for (int i = 0; i < n; i += size) { int left = i; int right = Math.min(i + size - 1, n - 1); int temp; while (left < right) { temp = arr[left]; arr[left] = arr[right]; arr[right] = temp; left += 1; right -= 1; } }
然后显示修改后的数组。演示此过程的代码段如下所示。
System.out.print("\nModified array is: "); for (int i = 0; i < n; i++) System.out.print(arr[i] + " ");