Tuesday, May 1, 2018

Reverse an integer array !!

Problem statement:  Reverse an integer array in java !
Using  for Loop:
  1. public class ReverseNumberArray {
  2. public static void main(String[] args) {
  3. int a[] = { 2, 4, 6, 7, 3, 56, 34 };
  4. for (int i = 0; i < a.length / 2; i++) {
  5. int temp = a[i];
  6. a[i] = a[a.length - 1 - i];
  7. a[a.length - 1 - i] = temp;
  8. }
  9. for (int i : a) {
  10. System.out.print(i + " ");
  11. }
  12. }
  13. }
Output: 
34 56 3 7 6 4 2 
Time complexity: O(n/2)

Using while Loop:
  1. public class ReverseNumberArray {

  2. public static void main(String[] args) {
  3. int a[] = { 2, 4, 6, 7, 3, 56, 34 };

  4. int end = a.length - 1;
  5. int start = 0;
  6. Object temp;
  7. while (start < end) {
  8. temp = a[start];
  9. a[start] = a[end];
  10. a[end] = (int) temp;
  11. start++;
  12. end--;
  13. }
  14. for (int i : a) {
  15. System.out.print(i + " ");
  16. }
  17. }
  18. }
Output: 
34 56 3 7 6 4 2 
Time complexity: O(n/2)

Using Java 8 Stream API:
  1. import java.util.stream.IntStream;

  2. public class ReverseArrayUsingStream {
  3. public static void main(String[] args) {
  4. Integer a[] = { 2, 4, 6, 7, 3, 56, 34 };
  5. reverseUsingStream(a);
  6. }

  7. static void reverseUsingStream(Object a[]) {

  8. Object rev[] = IntStream.rangeClosed(1, a.length).mapToObj(i -> a[a.length - i]).toArray();
  9. for (Object s : rev) {
  10. System.out.print(s + " ");
  11. }
  12. }
  13. }
Using Collections.reverse():

  1. import java.util.List;
  2. import java.util.Arrays;
  3. import java.util.Collections;

  4. public class ReverseArrayCollections {
  5. public static void main(String[] args) {

  6. Object a[] = { 2, 4, 6, 7, 3, 56, 34 };
  7. reverseUsingCollectionsUtils(a);
  8. }
  9. static void reverseUsingCollectionsUtils(Object[] array) {
  10. List<Object> list = Arrays.asList(array);
  11. Collections.reverse(list);
  12. for (Object i : list) {
  13. System.out.print(i + " ");
  14. }
  15. }
  16. }

Output:
34 56 3 7 6 4 2 

No comments:

Post a Comment

Blueprint for self-improvement

To learn faster: Make the process fun To understand yourself : Write To understand the world better : Read To build deeper connection : Lis...