Array Random Sorting

Status
You're currently viewing only nsample's posts. Click here to go back to viewing the entire thread.
Not open for further replies.
I would definitely recommend not looking at Knuth. You're shuffling cards here; it's not hard. I'll bet that the following method is "as random" and "as fast" as any other method you'll find.

I know no one seems to read the preceding posts in this forum, but for the record, here it is again:

Code:
  int j;
  for (int i = 0 ; i < 52 ; i++) {
    j = random.nextInt() % 52;
    swap(Deck[i], Deck[j]);
  }
 
I would definitely recommend not looking at Knuth. You're shuffling cards here; it's not hard.

Huh. Why not? An algorithm is there, after all; it's even referenced as an algorithm to "randomly shuffle cards" if I remember correctly.

Heh! :) Well, the main reason is (as stated previously) "you're shuffling cards here; it's not hard."

Sometimes, we built our own mental traps. One of those traps is the "appeal to authority", rather than simply trusting in yourself, fo even the simplest problems. "Look at Knuth" is a cop-out, and will take vastly longer than you need for the stated problem. Cop-outs tend to be that way, though... they give you the right answer, but at inflated costs.

Think about this way: do you refer to the owner's manual every time you put gas in your vehicle? Or do you trust that it's simple enough to fill the tank without referring to Knuth? (Err, I mean the owner's manual.)
 
So, I went downstairs... even got as far into this process as returning to Knuth's original presentation of the issue (Seminumerical Algorithms, page 139).

It turns out that it's the identical algorithm to what I presented. Sometimes things look super-simple and obvious for one reason: they are. (It also turns out that it's the same algorithm used in std::random_shuffle.)

For those keeping score, the algorithm is O(n), unlike the sorters who run in O(n log n), and the pigeon-holers who run in O(n^2). ;)
 
Big O analysis of finding that 52nd card?

Completely random. It might pick it first, or pick a million other cards first. In actual use, however, the loop ran instantly (in Java) when asked to produce 52 different cards.

If the algorithm needed to be scalable, I probably wouldn't do it that way. With only 52 cards, however, it just wasn't a problem.

Actually, for the 52nd card itself, it's O(n), not random. Sorting an entire deck that way ins O(n^2). That's what big omega notation is about... characterizing processes, even random ones.
 
Status
You're currently viewing only nsample's posts. Click here to go back to viewing the entire thread.
Not open for further replies.