Reverse a String in less than O(n) time complexity and without using any loop

Here is a Java program which reverses a character array in < O(n) time complexity. Here we are using recursion for reversing the characters. We traverse till the middle of the array to get the complete reverse array. Below is the Java code.

ReverseString.java
import java.util.Arrays;

public class ReverseString {

    private static int size = 0;
    private static int length = 0;
    public static void main(String[] args) {

        char[] a = {'s','h','i','m','p','u'};
        length = a.length;
        System.out.println("Original String is : " + Arrays.toString(a));
        if(length > 1){
            a = reverse(a,0);
        }
        System.out.println("String after reversal : " + Arrays.toString(a));
    }

    private static char[] reverse(char[] a, int index) {

        if(size == a.length/2){
            return a;
        }
        char temp = a[index];
        a[index] = a[length-1];
        a[length-1] = temp;
        length--;
        size++;
        return reverse(a, index+1);
    }
}
SHARE

    Blogger Comment
    Facebook Comment

0 comments :

Post a Comment