logo

הפוך מערך ב-Java

במדריך זה, נדון כיצד ניתן להפוך מערך ב-Java . בקלט, ניתן מערך שלמים, והמשימה היא להפוך את מערך הקלט. היפוך מערך פירושו שהאלמנט האחרון של מערך הקלט צריך להיות האלמנט הראשון של המערך ההפוך, האלמנט השני האחרון של מערך הקלט צריך להיות האלמנט השני של המערך ההפוך, וכן הלאה. שימו לב לדוגמאות הבאות.

דוגמה 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: שימוש במערך עזר

אנחנו יכולים לעבור את המערך מהסוף להתחלה, כלומר בסדר הפוך, ולאחסן את האלמנט שמצביע על ידי אינדקס הלולאה במערך העזר. מערך העזר מכיל כעת את הרכיבים של מערך הקלט בסדר הפוך. לאחר מכן, נוכל להציג את מערך העזר בקונסולה. ראה את התוכנית הבאה.

bash לקרוא קובץ

שם קובץ: 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: שימוש בשני מצביעים

נוכל גם להשתמש בשני מצביעים כדי להפוך את מערך הקלט. המצביע הראשון יעבור לאלמנט הראשון של המערך. המצביע השני יצביע על האלמנט האחרון של מערך הקלט. כעת נתחיל להחליף אלמנטים המצביעים על ידי שני המצביעים הללו. לאחר ההחלפה, המצביע השני ינוע לכיוון שמאלה, והמצביע הראשון ינוע לכיוון ימינה. כאשר שני המצביעים הללו נפגשים או חוצים זה את זה, אנו מפסיקים את ההחלפה, והמערך שאנו מקבלים הוא המערך ההפוך של מערך הקלט.

שם קובץ: 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: שימוש ב-Stack

מכיוון ש-Stack עובד על עיקרון LIFO (Last In First Out), ניתן להשתמש בו כדי להפוך את מערך הקלט. כל שעלינו לעשות הוא לשים את כל האלמנטים של מערך הקלט בערימה, החל משמאל לימין. נעשה זאת באמצעות לולאה.

מחרוזת פורמט java

שם קובץ: 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).

שימוש ברקורסיה

גם באמצעות רקורסיה נוכל להשיג את אותה תוצאה. שימו לב לדברים הבאים.

שם קובץ: 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]); נכתב לאחר שהקריאה הרקורסיבית נכנסת לערימה (שים לב שהמחסנית מרומזת במקרה זה). לכן, כאשר המקרה הבסיסי נפגע בקריאה הרקורסיבית, מתרחשת התנתקות מחסנית, וכל מה שיש בערימה קופץ החוצה. האלמנט האחרון נכנס לערימה במהלך הקריאה הרקורסיבית האחרונה. לכן, האלמנט האחרון קופץ ראשון. ואז האלמנט הלפני אחרון יוצא החוצה, וכן הלאה. ההצהרה reverseArr.add(arr[i]); חנויות שהוקפץ אלמנט. בסופו של דבר, אנו מציגים את האלמנטים המאוחסנים ברשימה reverseArr .

ניתוח מורכבות: זהה לתוכנית הראשונה של גישה-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;>

ניתוח מורכבות: התוכנית משתמשת Collections.reverse() שיטה שהופכת את הרשימה בזמן ליניארי, מה שהופך את הזמן למורכבות של התוכנית O(n). התוכנית משתמשת ב-list, מה שהופך את המרחב למורכבות של התוכנית O(n), כאשר n הוא המספר הכולל של האלמנטים הקיימים במערך.

מי זה פרדי כספית

הערה 1: Collections.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;>

ניתוח מורכבות: מורכבות הזמן והמרחב של התוכנית זהה לתוכנית הקודמת.