3 ways to reverse array in Java


/ Published in: Java
Save to your folder(s)

3 ways to reverse array in Java


Copy this code and paste it in your HTML
  1. import java.util.Arrays;
  2. public class Practive{
  3. public static void main (String[] args)
  4. {
  5. int [] array = new int[] {23,45,34,54,67,78};
  6. System.out.println("Original array:");
  7. System.out.println(Arrays.toString(array));
  8. //reverse method 1:
  9. int i =0;
  10. while ( i< (array.length)/2){
  11. for (int j = array.length-1; j>i;j--){
  12. int tempf = array[i];
  13. int tempb = array[j];
  14. array[i] = tempb;
  15. array[j]= tempf;
  16. i++;
  17. System.out.println("Reverse array");
  18. System.out.println(Arrays.toString(array));
  19. }
  20.  
  21.  
  22. }
  23.  
  24.  
  25.  
  26. }
  27.  
  28. }
  29.  
  30.  
  31. /*
  32. //reverse method 2:
  33. import java.util.Arrays;
  34. public class Practive{
  35. public static void main (String[] args)
  36. {
  37. int [] array = new int[] {23,45,34,54,67,78};
  38. System.out.println("Original array:");
  39. System.out.println(Arrays.toString(array));
  40. //reverse
  41. for (int i =0; i< (array.length)/2; i++){
  42. for (int j = array.length-1; j>i;j--){
  43. int tempf = array[i];
  44. int tempb = array[j];
  45. array[i] = tempb;
  46. array[j]= tempf;
  47. i++;
  48. System.out.println("Reverse array");
  49. System.out.println(Arrays.toString(array));
  50. }
  51.  
  52.  
  53. }
  54.  
  55. }
  56.  
  57. }
  58.  
  59. */
  60.  
  61.  
  62. /*
  63. import java.util.Arrays;
  64. public class Practive{
  65. public static void main (String[] args)
  66. {
  67. int [] array = new int[] {23,45,34,54,67,78};
  68. System.out.println("Original array:");
  69. System.out.println(Arrays.toString(array));
  70. //reverse method 3
  71. for (int i =0; i< (array.length)/2; i++){
  72. int temp = array[i];
  73. array[i] = array[array.length -1 -i];
  74. array[array.length-1-i]= temp;
  75. System.out.println("Reverse array");
  76. System.out.println(Arrays.toString(array));
  77. }
  78.  
  79.  
  80. }
  81.  
  82. }
  83. */

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.