数组可以反转到给定位置pos,其余数组不变。一个例子如下:
Array = 1 2 3 4 5 6 7 8 9 10 Position = 6 Modified array = 6 5 4 3 2 1 7 8 9 10
演示此的程序如下所示-
public class Example { public static void main(String args[]) { int[] arr = {1, 2, 3, 4, 5, 6, 7 ,8 ,9, 10}; int n = arr.length; int pos = 6; int temp; if (pos > n) { System.out.println( "Invalid...pos cannot be greater than n"); return; } System.out.print( "Initial array is: "); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); for (int i = 0; i < pos / 2; i++) { temp = arr[i]; arr[i] = arr[pos - i - 1]; arr[pos - i - 1] = temp; } System.out.print( "\nModified array is: "); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " "); } }
输出结果
Initial array is: 1 2 3 4 5 6 7 8 9 10 Modified array is: 6 5 4 3 2 1 7 8 9 10
现在让我们了解上面的程序。
如果位置大于数组的长度,则这是一个错误并被打印。否则,首先打印原始数组。证明这一点的代码片段如下所示-
if (pos > n) { System.out.println( "Invalid...pos cannot be greater than n"); return; } System.out.print( "Initial array is: "); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " ");
现在,使用for循环将数组反转到pos。然后显示修改后的数组。证明这一点的代码片段如下所示-
for (int i = 0; i < pos / 2; i++) { temp = arr[i]; arr[i] = arr[pos - i - 1]; arr[pos - i - 1] = temp; } System.out.print( "\nModified array is: "); for (int i = 0; i < n; ++i) System.out.print(arr[i] + " ");