Skip to content

Instantly share code, notes, and snippets.

@tenifni
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tenifni/8b5bccd689b35a50ea1f to your computer and use it in GitHub Desktop.
Save tenifni/8b5bccd689b35a50ea1f to your computer and use it in GitHub Desktop.
3 ways to reverse array in Java
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