Skip to main content
Engineering LibreTexts

4.6: Merging Decks

  • Page ID
    15296
  • The next helper method we need is merge, which takes two sorted subdecks and returns a new deck containing all cards from both decks, in order. Here’s what the algorithm looks like in pseudocode, assuming the subdecks are named d1 and d2:

    public static Deck merge(Deck d1, Deck d2) {
        // create a new deck big enough for all the cards
    
        // use the index i to keep track of where we are at in
        // the first deck, and the index j for the second deck
        int i = 0;
        int j = 0;
        // the index k traverses the result deck
        for (int k = 0; k < result.cards.length; k++) {
    
            // if d1 is empty, d2 wins
            // if d2 is empty, d1 wins
            // otherwise, compare the two cards
    
            // add the winner to the new deck at position k
            // increment either i or j
        }
        // return the new deck
    }
    

    One of the exercises at the end of the chapter asks you to implement merge.

    • Was this article helpful?