简体   繁体   中英

Reversing an array of ints without any loop

I would like to write a concise code that reverse an array of ints without using any loops . By "reversing" I mean the following: [1, 4, 3, 7, 2] -> [2, 7, 3, 4, 1] . I think that IntStream could be helpful here: it should be possible to "catch" a finite stream and proceed with it like with a stack (LIFO). Unfortunately I can't - could you please help?

Any loop can be replaced with recursion .

Hire is an example.

import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;

class RecursionReverseArray {


    private static <T> void reverseImpl(T[] arr,int lhsIdx, int rhsIdx) {
        if(lhsIdx == rhsIdx)
            return;
        T tmp = arr[lhsIdx];
        arr[lhsIdx] = arr[rhsIdx];
        arr[rhsIdx] = tmp;
        reverceImpl(arr, ++lhsIdx, --rhsIdx);
    }

    public static <T> void reverse(T[] arr) {
        reverseImpl(arr, 0, arr.length-1);
    }

    @Test
    void test() {
        Integer[] actual = {9,8,7,6,5,4,3,2,1};
        Integer[] expected = {1,2,3,4,5,6,7,8,9};
        reverse(actual);
        assertArrayEquals(expected, actual);
    }

} 

As well as with Java 8+ you can use reverse order stream API .

If you don't want to use loops, you can use recursions if you want. Here is a code written using recursion.

CODE

import java.io.*;

class ReverseArray {

static void rvereseArray(int arr[], int start, int end) 
{ 
    int temp; 
    if (start >= end) 
        return; 
    temp = arr[start]; 
    arr[start] = arr[end]; 
    arr[end] = temp; 
    rvereseArray(arr, start+1, end-1); 
} 

static void printArray(int arr[], int size) 
{ 
    for (int i=0; i < size; i++) 
        System.out.print(arr[i] + " "); 
    System.out.println(""); 
} 

public static void main (String[] args) { 
    int arr[] = {1, 2, 3, 4, 5, 6}; 
    printArray(arr, 6); 
    rvereseArray(arr, 0, 5); 
    System.out.println("Reversed array is "); 
    printArray(arr, 6); 
} 

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM