Skip to main content
Tweeted twitter.com/#!/StackCodeReview/status/59405643630649344
edited tags
Link
David Harkness
  • 8.9k
  • 1
  • 27
  • 44
Source Link
Raptrex
  • 195
  • 4

How can I make my decrypt method more efficient?

I am making a simple transposition cipher. I am testing the program with the word "computer" with the secret key "5,2,8,3,7,1,4,6", where the encrypt method will put the 5th letter 'u' in the first position, 2nd letter 'o' in 2nd position, 8th letter 'r' in 3rd position...

So the output would be:
original: computer
encrypted:uormecpt
decrypted:computer

Right now my decrypt method is of O(n^2). How can I make this faster?

Where char[] y would be uormecpt. The z[j] - 1 is the offset as my iterator starts from 0, but my key starts at 1.

public static char[] decrypt(char[] y, int[] z)
{
    char[] decrypted = new char[y.length];
    
    for (int i = 0; i < y.length; i++)
    {
        for (int j = 0; j < y.length; j++)
        {
            if (i == z[j]-1)
                decrypted[i] = y[j];
        }
    }
    
    return decrypted;
}