Search

Friday, May 26, 2017

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);
    }
}

No comments:

Post a Comment

Featured Post

ClassNotFoundException vs. NoClassDefFoundError

This is a very common question in Java interviews. Here we will learn to distinguish between two similar, but different problems that ca...