Created
June 14, 2017 07:34
-
-
Save anil477/94e5d22ffea9a40db8e34da5fcb4052a to your computer and use it in GitHub Desktop.
Reverse array - iterative and recursive
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.io.*; | |
import java.util.*; | |
class reverse | |
{ | |
public void iterative(int a[], int start, int end) | |
{ | |
int temp; | |
while(start < end) { | |
temp = a[end]; | |
a[end] = a[start]; | |
a[start] = temp; | |
start++; | |
end--; | |
}; | |
System.out.println("reversed iterative"); | |
for(int k:a) { | |
System.out.println(k); | |
} | |
} | |
public static void recursive(int a[], int start, int end) | |
{ | |
if (start >= end) | |
return; | |
int temp = a[end]; | |
a[end] = a[start]; | |
a[start] = temp; | |
recursive(a, ++start, --end); | |
} | |
public static void main(String[] args) | |
{ | |
reverse obj = new reverse(); | |
int arr[] = {1, 2, 3, 4, 5, 6, 7}; | |
int n = arr.length; | |
obj.iterative(arr, 0, n-1); | |
recursive(arr, 0, n-1); | |
// same array reversed twice | |
System.out.println("reversed recursive"); | |
for(int k:arr) { | |
System.out.println(k); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment