Quote:Original post by toogreat4u
Anyhow consider the fact that up to this point (in the text I am reading) there has been no mention of arrays
That's fine; you don't need anything like that here.
Quote:or sorting algorithms yet.
That's also fine; the input is already sorted, and your "merge" operation will automatically sort the output.
Quote:So my problem is for some reason I am having a severe brain cramp and can't figure out how to read these two files in correctly.
First, sketch out the algorithm. I want you to try the following:
First, shuffle a deck of cards, and split it into two halves (they don't have to be the same size).
Sort each half of the deck (in whatever way you like) in a consistent order - e.g. clubs 2 through ace, then diamonds, hearts and spades. Set up the two halves in front of you with the cards face up, so that the 2 of clubs is on the top of one of the two decks. (That is, each deck is sorted from "smallest" to "largest", with smallest on top.)
Now, merge the decks, by - at every step - taking the smaller of the two cards on top of the 'input' decks, and putting it
face down on top of an 'output' deck. One of the inputs will run out before the other; at that point, you can just start drawing cards one at a time from the other input.
Now, flip over the 'output'. (The thing about putting them face down and then flippin the deck is so that the first card you put in the output ends up on top, just as with a file - the first thing you write to a file is at the beginning of the file.) Notice that it is now completely sorted from smallest to largest.
So, how do we do this in code?
Well, we need to open the two input streams, and check the "top card" of each by reading it into a variable. Then we need to run a loop that takes the smaller of the two "showing" cards, puts it in the output, and "reveals" the next number in the file whose value we took, by reading it. (That "revealing" step is automatic with the actual decks of cards.) If we can't reveal another card, it's because that file is done; so we exit this loop, and enter another one to just copy values from the other file.