logo

Java で配列を反転する

このチュートリアルでは、その方法について説明します。 Javaで配列を反転する 。入力では整数配列が指定されており、タスクは入力配列を反転することです。配列を反転するとは、入力配列の最後の要素が反転された配列の最初の要素になること、入力配列の最後から 2 番目の要素が反転された配列の 2 番目の要素になることなどを意味します。次の例に注目してください。

例 1:

入力:

ネットワークオペレーティングシステム

arr[] = {1、2、3、4、5、6、7、8}

出力

例 2:

入力:

arr[] = {4、8、3、9、0、1}

出力:

arr[] = {1、0、9、3、8、4}

アプローチ 1: 補助配列の使用

配列を端から先頭まで、つまり逆の順序で走査し、ループ インデックスが指す要素を補助配列に格納できます。補助配列には、入力配列の要素が逆の順序で含まれるようになりました。その後、補助配列をコンソールに表示できます。次のプログラムを参照してください。

ファイル名: ReverseArr.java

 public class ReverseArr { // method for reversing an array public int[] reverseArray(int arr[]) { // computing the size of the array arr int size = arr.length; // auxiliary array for reversing the // elements of the array arr int temp[] = new int[size]; int index = 0; for(int i = size - 1; i &gt;= 0; i--) { temp[i] = arr[index]; index = index + 1; } return temp; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr ReverseArr obj = new ReverseArr(); // input array - 1 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; int ans[] = obj.reverseArray(arr); System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + ' '); } system.out.println(); system.out.println('the reversed array is: for(int i="0;" < len; system.out.print(ans[i] system.out.println('
 input - int arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" ans1[]="obj.reverseArray(arr1);" system.out.println('for array: system.out.print(arr1[i] system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> A for loop is required to reverse the array, which makes the time complexity of the program O(n). Also, an auxiliary array is required to reverse the array making the space complexity of the program O(n), where n is the total number of elements present in the array.</p> <h2>Approach 2: Using Two Pointers</h2> <p>We can also use two pointers to reverse the input array. The first pointer will go to the first element of the array. The second pointer will point to the last element of the input array. Now we will start swapping elements pointed by these two pointers. After swapping, the second pointer will move in the leftward direction, and the first pointer will move in the rightward direction. When these two pointers meet or cross each other, we stop the swapping, and the array we get is the reversed array of the input array.</p> <p> <strong>FileName:</strong> ReverseArr1.java</p> <pre> public class ReverseArr1 { // method for reversing an array public int[] reverseArray(int arr[]) { // computing the size of the array arr int size = arr.length; // two pointers for reversing // the input array int ptr1 = 0; int ptr2 = size - 1; // reversing the input array // using a while loop while(ptr1 <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The time complexity of the program is the same as the previous program. There is no extra space used in the program, making the space complexity of the program O(1).</p> <h2>Approach 3: Using Stack</h2> <p>Since a Stack works on the LIFO (Last In First Out) principle, it can be used to reverse the input array. All we have to do is to put all the elements of the input array in the stack, starting from left to right. We will do it using a loop.</p> <p> <strong>FileName:</strong> ReverseArr2.java</p> <pre> // importing Stack import java.util.Stack; public class ReverseArr2 { // method for reversing an array public int[] reverseArray(int arr[]) { // computing the size of the array arr int size = arr.length; Stack stk = new Stack(); // pusing all the elements into stack // starting from left for(int i = 0; i <size; 1 2 i++) { stk.push(arr[i]); } int i="0;" while(!stk.isempty()) ele="stk.pop();" arr[i]="ele;" + 1; return arr; main method public static void main(string argvs[]) creating an object of the class reversearr2 obj="new" reversearr2(); input array - arr[]="{1," 2, 3, 4, 5, 6, 7, 8}; computing length len="arr.length;" system.out.println('for array: '); for(int < len; system.out.print(arr[i] ' ans[]="obj.reverseArray(arr);" system.out.println(); system.out.println('the reversed is: system.out.print(ans[i] system.out.println('
 arr1[]="{4," 8, 9, 0, 1}; system.out.print(arr1[i] ans1[]="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The time complexity of the program is the same as the previous program. There is stack used in the program, making the space complexity of the program O(n).</p> <h3>Using Recursion</h3> <p>Using recursion also, we can achieve the same result. Observe the following.</p> <p> <strong>FileName:</strong> ReverseArr3.java</p> <pre> // importing ArrayList import java.util.ArrayList; public class ReverseArr3 { ArrayList reverseArr; // constructor of the class ReverseArr3() { reverseArr = new ArrayList(); } // method for reversing an array public void reverseArray(int arr[], int i, int size) { // dealing with the base case if(i &gt;= size) { return; } // recursively calling the method reverseArray(arr, i + 1, size); reverseArr.add(arr[i]); } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr3 ReverseArr3 obj = new ReverseArr3(); // input array - 1 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 0 2 i++) { system.out.print(arr[i] + ' '); } obj.reversearray(arr, , len); system.out.println(); system.out.println('the reversed array is: for(int i="0;" < len; system.out.print(obj.reversearr.get(i) system.out.println('
 obj="new" reversearr3(); input - int arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println('for array: system.out.print(arr1[i] obj.reversearray(arr1, pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Explanation:</strong> The statement <em>reverseArr.add(arr[i]);</em> is written after the recursive call goes in the stack (note that the stack is implicit in this case). So, when the base case is hit in the recursive call, stack unwinding happens, and whatever is there in the stack pops out. The last element goes into the stack during the last recursive call. Therefore, the last element is popped out first. Then the penultimate element is popped out, and so on. The statement <em>reverseArr.add(arr[i]);</em> stores that popped element. In the end, we are displaying the elements that are stored in the list <em>reverseArr</em> .</p> <p> <strong>Complexity Analysis:</strong> Same as the first program of approach-3.</p> <h2>Approach 4: Using Collections.reverse() method</h2> <p>The build method Collections.reverse() can be used to reverse the list. The use of it is shown in the following program.</p> <p> <strong>FileName:</strong> ReverseArr4.java</p> <pre> // importing Collections, Arrays, ArrayList &amp; List import java.util.Collections; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class ReverseArr4 { // method for reversing an array public List reverseArray(Integer arr[]) { List l = (Arrays.asList(arr)); Collections.reverse(l); return l; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr4 ReverseArr4 obj = new ReverseArr4(); // input array - 1 Integer arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + ' '); } list ans="obj.reverseArray(arr);" system.out.println(); system.out.println('the reversed array is: for(int i="0;" < len; system.out.print(ans.get(i) system.out.println('
 input - integer arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println('for array: system.out.print(arr1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The program uses <em>Collections.reverse()</em> method that reverses the list in linear time, making the time complexity of the program O(n). The program uses using list, making the space complexity of the program O(n), where n is the total number of elements present in the array.</p> <h4>Note 1: <em>Collections.reverse()</em> method is also used to reverse the linked list.</h4> <h4>Note 2: All the approaches discussed above are applicable to different data types too.</h4> <h2>Approach 5: Using StringBuilder.append() method</h2> <p>It is evident from the heading that this approach is applicable to string arrays. Using the StringBuilder.append() method, we can reverse the string array. All we have to do is to start appending the string elements of the array from the last to the beginning.</p> <p> <strong>FileName:</strong> ReverseArr5.java</p> <pre> import java.util.*; public class ReverseArr5 { // method for reversing an array public String[] reverseArray(String arr[]) { StringBuilder reversedSB = new StringBuilder(); for (int j = arr.length; j &gt; 0; j--) { reversedSB.append(arr[j - 1]).append(&apos; &apos;); }; String[] reversedArr = reversedSB.toString().split(&apos; &apos;); return reversedArr; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr5 ReverseArr5 obj = new ReverseArr5(); // input array - 1 String arr[] = {&apos;javaTpoint&apos;, &apos;is&apos;, &apos;the&apos;, &apos;best&apos;, &apos;website&apos;}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + ' '); } string[] ans="obj.reverseArray(arr);" system.out.println(); system.out.println('the reversed array is: for(int i="0;" < len; system.out.print(ans[i] system.out.println('
 input - string arr1[]="{&apos;India&apos;," 'is', 'my', 'country'}; computing the length len="arr1.length;" system.out.println('for array: system.out.print(arr1[i] ans1="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: javaTpoint is the best website The reversed array is: website best the is javaTpoint For the input array: India is my country The reversed array is: country my is India </pre> <p> <strong>Complexity Analysis:</strong> The time and space complexity of the program is the same as the previous program.</p> <hr></len;></pre></len;></pre></len;></pre></size;></pre></pre></len;>

複雑さの分析: 配列を反転するには for ループが必要となるため、プログラムの時間計算量は O(n) になります。また、配列を反転するために補助配列が必要になり、プログラムの空間複雑度が O(n) になります。ここで、n は配列内に存在する要素の総数です。

アプローチ 2: 2 つのポインターを使用する

2 つのポインターを使用して入力配列を反転することもできます。最初のポインタは配列の最初の要素に移動します。 2 番目のポインターは、入力配列の最後の要素を指します。ここで、これら 2 つのポインターが指す要素の交換を開始します。交換後、2 番目のポインターは左方向に移動し、1 番目のポインターは右方向に移動します。これら 2 つのポインターが出会うか交差すると、スワップが停止され、取得される配列は入力配列の反転配列になります。

ファイル名: ReverseArr1.java

 public class ReverseArr1 { // method for reversing an array public int[] reverseArray(int arr[]) { // computing the size of the array arr int size = arr.length; // two pointers for reversing // the input array int ptr1 = 0; int ptr2 = size - 1; // reversing the input array // using a while loop while(ptr1 <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The time complexity of the program is the same as the previous program. There is no extra space used in the program, making the space complexity of the program O(1).</p> <h2>Approach 3: Using Stack</h2> <p>Since a Stack works on the LIFO (Last In First Out) principle, it can be used to reverse the input array. All we have to do is to put all the elements of the input array in the stack, starting from left to right. We will do it using a loop.</p> <p> <strong>FileName:</strong> ReverseArr2.java</p> <pre> // importing Stack import java.util.Stack; public class ReverseArr2 { // method for reversing an array public int[] reverseArray(int arr[]) { // computing the size of the array arr int size = arr.length; Stack stk = new Stack(); // pusing all the elements into stack // starting from left for(int i = 0; i <size; 1 2 i++) { stk.push(arr[i]); } int i="0;" while(!stk.isempty()) ele="stk.pop();" arr[i]="ele;" + 1; return arr; main method public static void main(string argvs[]) creating an object of the class reversearr2 obj="new" reversearr2(); input array - arr[]="{1," 2, 3, 4, 5, 6, 7, 8}; computing length len="arr.length;" system.out.println(\'for array: \'); for(int < len; system.out.print(arr[i] \' ans[]="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed is: system.out.print(ans[i] system.out.println(\'
 arr1[]="{4," 8, 9, 0, 1}; system.out.print(arr1[i] ans1[]="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The time complexity of the program is the same as the previous program. There is stack used in the program, making the space complexity of the program O(n).</p> <h3>Using Recursion</h3> <p>Using recursion also, we can achieve the same result. Observe the following.</p> <p> <strong>FileName:</strong> ReverseArr3.java</p> <pre> // importing ArrayList import java.util.ArrayList; public class ReverseArr3 { ArrayList reverseArr; // constructor of the class ReverseArr3() { reverseArr = new ArrayList(); } // method for reversing an array public void reverseArray(int arr[], int i, int size) { // dealing with the base case if(i &gt;= size) { return; } // recursively calling the method reverseArray(arr, i + 1, size); reverseArr.add(arr[i]); } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr3 ReverseArr3 obj = new ReverseArr3(); // input array - 1 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 0 2 i++) { system.out.print(arr[i] + \' \'); } obj.reversearray(arr, , len); system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(obj.reversearr.get(i) system.out.println(\'
 obj="new" reversearr3(); input - int arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] obj.reversearray(arr1, pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Explanation:</strong> The statement <em>reverseArr.add(arr[i]);</em> is written after the recursive call goes in the stack (note that the stack is implicit in this case). So, when the base case is hit in the recursive call, stack unwinding happens, and whatever is there in the stack pops out. The last element goes into the stack during the last recursive call. Therefore, the last element is popped out first. Then the penultimate element is popped out, and so on. The statement <em>reverseArr.add(arr[i]);</em> stores that popped element. In the end, we are displaying the elements that are stored in the list <em>reverseArr</em> .</p> <p> <strong>Complexity Analysis:</strong> Same as the first program of approach-3.</p> <h2>Approach 4: Using Collections.reverse() method</h2> <p>The build method Collections.reverse() can be used to reverse the list. The use of it is shown in the following program.</p> <p> <strong>FileName:</strong> ReverseArr4.java</p> <pre> // importing Collections, Arrays, ArrayList &amp; List import java.util.Collections; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class ReverseArr4 { // method for reversing an array public List reverseArray(Integer arr[]) { List l = (Arrays.asList(arr)); Collections.reverse(l); return l; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr4 ReverseArr4 obj = new ReverseArr4(); // input array - 1 Integer arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \' \'); } list ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(ans.get(i) system.out.println(\'
 input - integer arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The program uses <em>Collections.reverse()</em> method that reverses the list in linear time, making the time complexity of the program O(n). The program uses using list, making the space complexity of the program O(n), where n is the total number of elements present in the array.</p> <h4>Note 1: <em>Collections.reverse()</em> method is also used to reverse the linked list.</h4> <h4>Note 2: All the approaches discussed above are applicable to different data types too.</h4> <h2>Approach 5: Using StringBuilder.append() method</h2> <p>It is evident from the heading that this approach is applicable to string arrays. Using the StringBuilder.append() method, we can reverse the string array. All we have to do is to start appending the string elements of the array from the last to the beginning.</p> <p> <strong>FileName:</strong> ReverseArr5.java</p> <pre> import java.util.*; public class ReverseArr5 { // method for reversing an array public String[] reverseArray(String arr[]) { StringBuilder reversedSB = new StringBuilder(); for (int j = arr.length; j &gt; 0; j--) { reversedSB.append(arr[j - 1]).append(&apos; &apos;); }; String[] reversedArr = reversedSB.toString().split(&apos; &apos;); return reversedArr; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr5 ReverseArr5 obj = new ReverseArr5(); // input array - 1 String arr[] = {&apos;javaTpoint&apos;, &apos;is&apos;, &apos;the&apos;, &apos;best&apos;, &apos;website&apos;}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \' \'); } string[] ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(ans[i] system.out.println(\'
 input - string arr1[]="{&apos;India&apos;," \'is\', \'my\', \'country\'}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] ans1="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: javaTpoint is the best website The reversed array is: website best the is javaTpoint For the input array: India is my country The reversed array is: country my is India </pre> <p> <strong>Complexity Analysis:</strong> The time and space complexity of the program is the same as the previous program.</p> <hr></len;></pre></len;></pre></len;></pre></size;></pre>

複雑さの分析: プログラムの時間計算量は前のプログラムと同じです。プログラム内で余分なスペースが使用されないため、プログラムのスペースの複雑さは O(1) になります。

アプローチ 3: スタックの使用

スタックは LIFO (Last In First Out) 原理に基づいて動作するため、入力配列を反転するために使用できます。私たちがしなければならないことは、入力配列のすべての要素を左から右にスタックに入れることだけです。ループを使用して実行します。

ファイル名: ReverseArr2.java

 // importing Stack import java.util.Stack; public class ReverseArr2 { // method for reversing an array public int[] reverseArray(int arr[]) { // computing the size of the array arr int size = arr.length; Stack stk = new Stack(); // pusing all the elements into stack // starting from left for(int i = 0; i <size; 1 2 i++) { stk.push(arr[i]); } int i="0;" while(!stk.isempty()) ele="stk.pop();" arr[i]="ele;" + 1; return arr; main method public static void main(string argvs[]) creating an object of the class reversearr2 obj="new" reversearr2(); input array - arr[]="{1," 2, 3, 4, 5, 6, 7, 8}; computing length len="arr.length;" system.out.println(\'for array: \'); for(int < len; system.out.print(arr[i] \' ans[]="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed is: system.out.print(ans[i] system.out.println(\'
 arr1[]="{4," 8, 9, 0, 1}; system.out.print(arr1[i] ans1[]="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The time complexity of the program is the same as the previous program. There is stack used in the program, making the space complexity of the program O(n).</p> <h3>Using Recursion</h3> <p>Using recursion also, we can achieve the same result. Observe the following.</p> <p> <strong>FileName:</strong> ReverseArr3.java</p> <pre> // importing ArrayList import java.util.ArrayList; public class ReverseArr3 { ArrayList reverseArr; // constructor of the class ReverseArr3() { reverseArr = new ArrayList(); } // method for reversing an array public void reverseArray(int arr[], int i, int size) { // dealing with the base case if(i &gt;= size) { return; } // recursively calling the method reverseArray(arr, i + 1, size); reverseArr.add(arr[i]); } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr3 ReverseArr3 obj = new ReverseArr3(); // input array - 1 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 0 2 i++) { system.out.print(arr[i] + \' \'); } obj.reversearray(arr, , len); system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(obj.reversearr.get(i) system.out.println(\'
 obj="new" reversearr3(); input - int arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] obj.reversearray(arr1, pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Explanation:</strong> The statement <em>reverseArr.add(arr[i]);</em> is written after the recursive call goes in the stack (note that the stack is implicit in this case). So, when the base case is hit in the recursive call, stack unwinding happens, and whatever is there in the stack pops out. The last element goes into the stack during the last recursive call. Therefore, the last element is popped out first. Then the penultimate element is popped out, and so on. The statement <em>reverseArr.add(arr[i]);</em> stores that popped element. In the end, we are displaying the elements that are stored in the list <em>reverseArr</em> .</p> <p> <strong>Complexity Analysis:</strong> Same as the first program of approach-3.</p> <h2>Approach 4: Using Collections.reverse() method</h2> <p>The build method Collections.reverse() can be used to reverse the list. The use of it is shown in the following program.</p> <p> <strong>FileName:</strong> ReverseArr4.java</p> <pre> // importing Collections, Arrays, ArrayList &amp; List import java.util.Collections; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class ReverseArr4 { // method for reversing an array public List reverseArray(Integer arr[]) { List l = (Arrays.asList(arr)); Collections.reverse(l); return l; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr4 ReverseArr4 obj = new ReverseArr4(); // input array - 1 Integer arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \' \'); } list ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(ans.get(i) system.out.println(\'
 input - integer arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The program uses <em>Collections.reverse()</em> method that reverses the list in linear time, making the time complexity of the program O(n). The program uses using list, making the space complexity of the program O(n), where n is the total number of elements present in the array.</p> <h4>Note 1: <em>Collections.reverse()</em> method is also used to reverse the linked list.</h4> <h4>Note 2: All the approaches discussed above are applicable to different data types too.</h4> <h2>Approach 5: Using StringBuilder.append() method</h2> <p>It is evident from the heading that this approach is applicable to string arrays. Using the StringBuilder.append() method, we can reverse the string array. All we have to do is to start appending the string elements of the array from the last to the beginning.</p> <p> <strong>FileName:</strong> ReverseArr5.java</p> <pre> import java.util.*; public class ReverseArr5 { // method for reversing an array public String[] reverseArray(String arr[]) { StringBuilder reversedSB = new StringBuilder(); for (int j = arr.length; j &gt; 0; j--) { reversedSB.append(arr[j - 1]).append(&apos; &apos;); }; String[] reversedArr = reversedSB.toString().split(&apos; &apos;); return reversedArr; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr5 ReverseArr5 obj = new ReverseArr5(); // input array - 1 String arr[] = {&apos;javaTpoint&apos;, &apos;is&apos;, &apos;the&apos;, &apos;best&apos;, &apos;website&apos;}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \' \'); } string[] ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(ans[i] system.out.println(\'
 input - string arr1[]="{&apos;India&apos;," \'is\', \'my\', \'country\'}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] ans1="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: javaTpoint is the best website The reversed array is: website best the is javaTpoint For the input array: India is my country The reversed array is: country my is India </pre> <p> <strong>Complexity Analysis:</strong> The time and space complexity of the program is the same as the previous program.</p> <hr></len;></pre></len;></pre></len;></pre></size;>

複雑さの分析: プログラムの時間計算量は前のプログラムと同じです。プログラム内でスタックが使用されるため、プログラムの空間複雑度は O(n) になります。

jsonファイルを読む

再帰の使用

再帰を使用しても、同じ結果を得ることができます。以下の点に注意してください。

ファイル名: ReverseArr3.java

 // importing ArrayList import java.util.ArrayList; public class ReverseArr3 { ArrayList reverseArr; // constructor of the class ReverseArr3() { reverseArr = new ArrayList(); } // method for reversing an array public void reverseArray(int arr[], int i, int size) { // dealing with the base case if(i &gt;= size) { return; } // recursively calling the method reverseArray(arr, i + 1, size); reverseArr.add(arr[i]); } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr3 ReverseArr3 obj = new ReverseArr3(); // input array - 1 int arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 0 2 i++) { system.out.print(arr[i] + \' \'); } obj.reversearray(arr, , len); system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(obj.reversearr.get(i) system.out.println(\'
 obj="new" reversearr3(); input - int arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] obj.reversearray(arr1, pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Explanation:</strong> The statement <em>reverseArr.add(arr[i]);</em> is written after the recursive call goes in the stack (note that the stack is implicit in this case). So, when the base case is hit in the recursive call, stack unwinding happens, and whatever is there in the stack pops out. The last element goes into the stack during the last recursive call. Therefore, the last element is popped out first. Then the penultimate element is popped out, and so on. The statement <em>reverseArr.add(arr[i]);</em> stores that popped element. In the end, we are displaying the elements that are stored in the list <em>reverseArr</em> .</p> <p> <strong>Complexity Analysis:</strong> Same as the first program of approach-3.</p> <h2>Approach 4: Using Collections.reverse() method</h2> <p>The build method Collections.reverse() can be used to reverse the list. The use of it is shown in the following program.</p> <p> <strong>FileName:</strong> ReverseArr4.java</p> <pre> // importing Collections, Arrays, ArrayList &amp; List import java.util.Collections; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class ReverseArr4 { // method for reversing an array public List reverseArray(Integer arr[]) { List l = (Arrays.asList(arr)); Collections.reverse(l); return l; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr4 ReverseArr4 obj = new ReverseArr4(); // input array - 1 Integer arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \' \'); } list ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(ans.get(i) system.out.println(\'
 input - integer arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The program uses <em>Collections.reverse()</em> method that reverses the list in linear time, making the time complexity of the program O(n). The program uses using list, making the space complexity of the program O(n), where n is the total number of elements present in the array.</p> <h4>Note 1: <em>Collections.reverse()</em> method is also used to reverse the linked list.</h4> <h4>Note 2: All the approaches discussed above are applicable to different data types too.</h4> <h2>Approach 5: Using StringBuilder.append() method</h2> <p>It is evident from the heading that this approach is applicable to string arrays. Using the StringBuilder.append() method, we can reverse the string array. All we have to do is to start appending the string elements of the array from the last to the beginning.</p> <p> <strong>FileName:</strong> ReverseArr5.java</p> <pre> import java.util.*; public class ReverseArr5 { // method for reversing an array public String[] reverseArray(String arr[]) { StringBuilder reversedSB = new StringBuilder(); for (int j = arr.length; j &gt; 0; j--) { reversedSB.append(arr[j - 1]).append(&apos; &apos;); }; String[] reversedArr = reversedSB.toString().split(&apos; &apos;); return reversedArr; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr5 ReverseArr5 obj = new ReverseArr5(); // input array - 1 String arr[] = {&apos;javaTpoint&apos;, &apos;is&apos;, &apos;the&apos;, &apos;best&apos;, &apos;website&apos;}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \' \'); } string[] ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(ans[i] system.out.println(\'
 input - string arr1[]="{&apos;India&apos;," \'is\', \'my\', \'country\'}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] ans1="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: javaTpoint is the best website The reversed array is: website best the is javaTpoint For the input array: India is my country The reversed array is: country my is India </pre> <p> <strong>Complexity Analysis:</strong> The time and space complexity of the program is the same as the previous program.</p> <hr></len;></pre></len;></pre></len;>

説明: 声明 reverseArr.add(arr[i]); 再帰呼び出しがスタックに入った後に書き込まれます (この場合、スタックは暗黙的であることに注意してください)。したがって、再帰呼び出しで基本ケースがヒットすると、スタックの巻き戻しが発生し、スタック内にあるものはすべて飛び出します。最後の要素は、最後の再帰呼び出し中にスタックに入れられます。したがって、最後の要素が最初にポップアウトされます。次に、最後から 2 番目の要素がポップアウトされ、以下同様に続きます。声明 reverseArr.add(arr[i]); ポップされた要素を格納します。最後に、リストに保存されている要素を表示します。 逆方向矢印

複雑さの分析: アプローチ 3 の最初のプログラムと同じです。

アプローチ 4: Collections.reverse() メソッドを使用する

ビルド メソッド Collections.reverse() を使用してリストを逆にすることができます。その使用方法は次のプログラムで示されています。

ファイル名: ReverseArr4.java

 // importing Collections, Arrays, ArrayList &amp; List import java.util.Collections; import java.util.Arrays; import java.util.List; import java.util.ArrayList; public class ReverseArr4 { // method for reversing an array public List reverseArray(Integer arr[]) { List l = (Arrays.asList(arr)); Collections.reverse(l); return l; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr4 ReverseArr4 obj = new ReverseArr4(); // input array - 1 Integer arr[] = {1, 2, 3, 4, 5, 6, 7, 8}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \' \'); } list ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(ans.get(i) system.out.println(\'
 input - integer arr1[]="{4," 8, 3, 9, 0, 1}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: 1 2 3 4 5 6 7 8 The reversed array is: 8 7 6 5 4 3 2 1 For the input array: 4 8 3 9 0 1 The reversed array is: 1 0 9 3 8 4 </pre> <p> <strong>Complexity Analysis:</strong> The program uses <em>Collections.reverse()</em> method that reverses the list in linear time, making the time complexity of the program O(n). The program uses using list, making the space complexity of the program O(n), where n is the total number of elements present in the array.</p> <h4>Note 1: <em>Collections.reverse()</em> method is also used to reverse the linked list.</h4> <h4>Note 2: All the approaches discussed above are applicable to different data types too.</h4> <h2>Approach 5: Using StringBuilder.append() method</h2> <p>It is evident from the heading that this approach is applicable to string arrays. Using the StringBuilder.append() method, we can reverse the string array. All we have to do is to start appending the string elements of the array from the last to the beginning.</p> <p> <strong>FileName:</strong> ReverseArr5.java</p> <pre> import java.util.*; public class ReverseArr5 { // method for reversing an array public String[] reverseArray(String arr[]) { StringBuilder reversedSB = new StringBuilder(); for (int j = arr.length; j &gt; 0; j--) { reversedSB.append(arr[j - 1]).append(&apos; &apos;); }; String[] reversedArr = reversedSB.toString().split(&apos; &apos;); return reversedArr; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr5 ReverseArr5 obj = new ReverseArr5(); // input array - 1 String arr[] = {&apos;javaTpoint&apos;, &apos;is&apos;, &apos;the&apos;, &apos;best&apos;, &apos;website&apos;}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \' \'); } string[] ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\'the reversed array is: for(int i="0;" < len; system.out.print(ans[i] system.out.println(\'
 input - string arr1[]="{&apos;India&apos;," \'is\', \'my\', \'country\'}; computing the length len="arr1.length;" system.out.println(\'for array: system.out.print(arr1[i] ans1="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: javaTpoint is the best website The reversed array is: website best the is javaTpoint For the input array: India is my country The reversed array is: country my is India </pre> <p> <strong>Complexity Analysis:</strong> The time and space complexity of the program is the same as the previous program.</p> <hr></len;></pre></len;>

複雑さの分析: プログラムが使用するのは、 コレクション.reverse() リストを線形時間で反転し、プログラムの時間計算量を O(n) にするメソッドです。プログラムは using list を使用し、プログラムの空間複雑度を O(n) にします。ここで、n は配列内に存在する要素の総数です。

注1: コレクション.reverse() このメソッドは、リンクされたリストを逆にするためにも使用されます。

注 2: 上記で説明したすべてのアプローチは、さまざまなデータ型にも適用できます。

アプローチ 5: StringBuilder.append() メソッドを使用する

このアプローチが文字列配列に適用できることは、見出しから明らかです。 StringBuilder.append() メソッドを使用すると、文字列配列を反転できます。私たちがしなければならないことは、配列の文字列要素を最後から先頭に追加し始めることだけです。

ファイル名: ReverseArr5.java

 import java.util.*; public class ReverseArr5 { // method for reversing an array public String[] reverseArray(String arr[]) { StringBuilder reversedSB = new StringBuilder(); for (int j = arr.length; j &gt; 0; j--) { reversedSB.append(arr[j - 1]).append(&apos; &apos;); }; String[] reversedArr = reversedSB.toString().split(&apos; &apos;); return reversedArr; } // main method public static void main(String argvs[]) { // creating an object of the class ReverseArr5 ReverseArr5 obj = new ReverseArr5(); // input array - 1 String arr[] = {&apos;javaTpoint&apos;, &apos;is&apos;, &apos;the&apos;, &apos;best&apos;, &apos;website&apos;}; // computing the length int len = arr.length; System.out.println(&apos;For the input array: &apos;); for(int i = 0; i <len; 2 i++) { system.out.print(arr[i] + \\' \\'); } string[] ans="obj.reverseArray(arr);" system.out.println(); system.out.println(\\'the reversed array is: for(int i="0;" < len; system.out.print(ans[i] system.out.println(\\'
 input - string arr1[]="{&apos;India&apos;," \\'is\\', \\'my\\', \\'country\\'}; computing the length len="arr1.length;" system.out.println(\\'for array: system.out.print(arr1[i] ans1="obj.reverseArray(arr1);" system.out.print(ans1[i] pre> <p> <strong>Output:</strong> </p> <pre> For the input array: javaTpoint is the best website The reversed array is: website best the is javaTpoint For the input array: India is my country The reversed array is: country my is India </pre> <p> <strong>Complexity Analysis:</strong> The time and space complexity of the program is the same as the previous program.</p> <hr></len;>

複雑さの分析: プログラムの時間と空間の複雑さは前のプログラムと同じです。