Last active
August 29, 2015 14:27
-
-
Save tenifni/8b5bccd689b35a50ea1f to your computer and use it in GitHub Desktop.
3 ways to reverse array in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.Arrays; | |
public class Practive{ | |
public static void main (String[] args) | |
{ | |
int [] array = new int[] {23,45,34,54,67,78}; | |
System.out.println("Original array:"); | |
System.out.println(Arrays.toString(array)); | |
//reverse method 1: | |
int i =0; | |
while ( i< (array.length)/2){ | |
for (int j = array.length-1; j>i;j--){ | |
int tempf = array[i]; | |
int tempb = array[j]; | |
array[i] = tempb; | |
array[j]= tempf; | |
i++; | |
System.out.println("Reverse array"); | |
System.out.println(Arrays.toString(array)); | |
} | |
} | |
} | |
} | |
/* | |
//reverse method 2: | |
import java.util.Arrays; | |
public class Practive{ | |
public static void main (String[] args) | |
{ | |
int [] array = new int[] {23,45,34,54,67,78}; | |
System.out.println("Original array:"); | |
System.out.println(Arrays.toString(array)); | |
//reverse | |
for (int i =0; i< (array.length)/2; i++){ | |
for (int j = array.length-1; j>i;j--){ | |
int tempf = array[i]; | |
int tempb = array[j]; | |
array[i] = tempb; | |
array[j]= tempf; | |
i++; | |
System.out.println("Reverse array"); | |
System.out.println(Arrays.toString(array)); | |
} | |
} | |
} | |
} | |
*/ | |
/* | |
import java.util.Arrays; | |
public class Practive{ | |
public static void main (String[] args) | |
{ | |
int [] array = new int[] {23,45,34,54,67,78}; | |
System.out.println("Original array:"); | |
System.out.println(Arrays.toString(array)); | |
//reverse method 3 | |
for (int i =0; i< (array.length)/2; i++){ | |
int temp = array[i]; | |
array[i] = array[array.length -1 -i]; | |
array[array.length-1-i]= temp; | |
System.out.println("Reverse array"); | |
System.out.println(Arrays.toString(array)); | |
} | |
} | |
} | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment