Problem statement: Reverse an integer array in java !
Using for Loop:
Using for Loop:
- public class ReverseNumberArray {
- public static void main(String[] args) {
- int a[] = { 2, 4, 6, 7, 3, 56, 34 };
- for (int i = 0; i < a.length / 2; i++) {
- int temp = a[i];
- a[i] = a[a.length - 1 - i];
- a[a.length - 1 - i] = temp;
- }
- for (int i : a) {
- System.out.print(i + " ");
- }
- }
- }
Output:
34 56 3 7 6 4 2
Time complexity: O(n/2)
Using while Loop:
- public class ReverseNumberArray {
- public static void main(String[] args) {
- int a[] = { 2, 4, 6, 7, 3, 56, 34 };
- int end = a.length - 1;
- int start = 0;
- Object temp;
- while (start < end) {
- temp = a[start];
- a[start] = a[end];
- a[end] = (int) temp;
- start++;
- end--;
- }
- for (int i : a) {
- System.out.print(i + " ");
- }
- }
- }
Output:
34 56 3 7 6 4 2
Time complexity: O(n/2)
Using Java 8 Stream API:
Output:
34 56 3 7 6 4 2
Using Java 8 Stream API:
- import java.util.stream.IntStream;
- public class ReverseArrayUsingStream {
- public static void main(String[] args) {
- Integer a[] = { 2, 4, 6, 7, 3, 56, 34 };
- reverseUsingStream(a);
- }
- static void reverseUsingStream(Object a[]) {
- Object rev[] = IntStream.rangeClosed(1, a.length).mapToObj(i -> a[a.length - i]).toArray();
- for (Object s : rev) {
- System.out.print(s + " ");
- }
- }
- }
- import java.util.List;
- import java.util.Arrays;
- import java.util.Collections;
- public class ReverseArrayCollections {
- public static void main(String[] args) {
- Object a[] = { 2, 4, 6, 7, 3, 56, 34 };
- reverseUsingCollectionsUtils(a);
- }
- static void reverseUsingCollectionsUtils(Object[] array) {
- List<Object> list = Arrays.asList(array);
- Collections.reverse(list);
- for (Object i : list) {
- System.out.print(i + " ");
- }
- }
- }
Output:
34 56 3 7 6 4 2
No comments:
Post a Comment