logo

Reverter um array em Java

Neste tutorial, discutiremos como se pode reverter um array em Java . Na entrada, um array inteiro é fornecido e a tarefa é reverter o array de entrada. Reverter uma matriz significa que o último elemento da matriz de entrada deve ser o primeiro elemento da matriz invertida, o penúltimo elemento da matriz de entrada deve ser o segundo elemento da matriz invertida e assim por diante. Observe os exemplos a seguir.

Exemplo 1:

Entrada:

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

Saída

java matemática aleatória

Exemplo 2:

Entrada:

mysql esquerda juntar

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

Saída:

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

Abordagem 1: Usando uma matriz auxiliar

Podemos percorrer o array do final ao início, ou seja, na ordem inversa, e armazenar o elemento apontado pelo índice do loop no array auxiliar. A matriz auxiliar agora contém os elementos da matriz de entrada em ordem inversa. Depois disso, podemos exibir o array auxiliar no console. Veja o seguinte programa.

Nome do arquivo: 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;>

Análise de Complexidade: Um loop for é necessário para reverter o array, o que torna a complexidade de tempo do programa O(n). Além disso, um array auxiliar é necessário para reverter o array tornando a complexidade espacial do programa O(n), onde n é o número total de elementos presentes no array.

onclick javascript

Abordagem 2: Usando duas dicas

Também podemos usar dois ponteiros para reverter o array de entrada. O primeiro ponteiro irá para o primeiro elemento do array. O segundo ponteiro apontará para o último elemento da matriz de entrada. Agora começaremos a trocar os elementos apontados por esses dois ponteiros. Após a troca, o segundo ponteiro se moverá na direção esquerda e o primeiro ponteiro se moverá na direção direita. Quando esses dois ponteiros se encontram ou se cruzam, paramos a troca e o array que obtemos é o array invertido do array de entrada.

Nome do arquivo: 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>

Análise de Complexidade: A complexidade de tempo do programa é a mesma do programa anterior. Não há espaço extra usado no programa, tornando a complexidade de espaço do programa O(1).

Abordagem 3: Usando Stack

Como uma pilha funciona com base no princípio LIFO (Last In First Out), ela pode ser usada para reverter a matriz de entrada. Tudo o que precisamos fazer é colocar todos os elementos do array de entrada na pilha, começando da esquerda para a direita. Faremos isso usando um loop.

Nome do arquivo: ReverseArr2.java

núcleo 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;>

Análise de Complexidade: A complexidade de tempo do programa é a mesma do programa anterior. Existe uma pilha usada no programa, tornando a complexidade do espaço do programa O(n).

Usando recursão

Usando também a recursão, podemos obter o mesmo resultado. Observe o seguinte.

Nome do arquivo: ReverseArr3.java

lista de arrays de ordenação 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;>

Explicação: A declaração inverterArr.add(arr[i]); é escrito depois que a chamada recursiva vai para a pilha (observe que a pilha está implícita neste caso). Portanto, quando o caso base é atingido na chamada recursiva, ocorre o desenrolamento da pilha e tudo o que está na pilha aparece. O último elemento vai para a pilha durante a última chamada recursiva. Portanto, o último elemento é exibido primeiro. Em seguida, o penúltimo elemento é exibido e assim por diante. A declaração inverterArr.add(arr[i]); armazena esse elemento estourado. No final, estamos exibindo os elementos que estão armazenados na lista inverterArr .

Análise de Complexidade: Igual ao primeiro programa da abordagem 3.

Abordagem 4: Usando o método Collections.reverse()

O método de construção Collections.reverse() pode ser usado para reverter a lista. O uso dele é mostrado no programa a seguir.

Nome do arquivo: 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;>

Análise de Complexidade: O programa usa Coleções.reverse() método que inverte a lista em tempo linear, tornando a complexidade de tempo do programa O(n). O programa utiliza o uso de lista, tornando a complexidade espacial do programa O(n), onde n é o número total de elementos presentes no array.

Nota 1: Coleções.reverse() O método também é usado para reverter a lista vinculada.

Nota 2: Todas as abordagens discutidas acima também são aplicáveis ​​a diferentes tipos de dados.

Abordagem 5: Usando o método StringBuilder.append()

É evidente no título que esta abordagem é aplicável a matrizes de strings. Usando o método StringBuilder.append(), podemos reverter a matriz de strings. Tudo o que precisamos fazer é começar a anexar os elementos string do array do último ao início.

Nome do arquivo: 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;>

Análise de Complexidade: A complexidade de tempo e espaço do programa é a mesma do programa anterior.