HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Shuffling a JSON array in Java

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
jsonarrayjavashuffling

Problem

Since I did not get a satisfactory answer here (and I really needed to get it going on this weekend), I decided to implement my own Fisher–Yates shuffle, porting the code I found in other SO posts. I know my programming technique is far from optimal, so I decided to post this here.

What do you think? Can it be improved?

public static JSONArray shuffleJsonArray (JSONArray array) throws JSONException {
    // Implementing Fisher–Yates shuffle
        Random rnd = new Random();
        for (int i = array.length() - 1; i >= 0; i--)
        {
          int j = rnd.nextInt(i + 1);
          // Simple swap
          Object object = array.get(j);
          array.put(j, array.get(i));
          array.put(i, object);
        }
    return array;
}

Solution

It runs in \$O(n)\$ time so I'm not sure there's a way to improve this. It looks like you've implemented the algorithm pretty well, according the Fisher-Yates shuffle.

You might consider not using Object if you can use the type that's stored in the array instead.

I also thought I read somewhere that it should be safe to loop to \$n/2\$ instead of \$n\$ (because you're swapping with elements from \$1 \cdots n\$ so in theory, you shouldn't need to swap every element), but I don't have hard proof of that, so you take your chances ;)

Context

StackExchange Code Review Q#1640, answer score: 2

Revisions (0)

No revisions yet.