title: Sorting Subarrays in C Sorts Entire Array Instead?
body: <p>So in this little game I wrote I have a deck of <code>n_C</code> cards, each with a unique integer value. 
  There are <code>n_P</code> players each holding <code>n_H</code> cards in their hand.</p>
  
  <p>The deck and the hands share an array, like so:
  Player <code>i_P</code>'s hand contains all cards from from <code>deck[i_P * n_H</code> to <code>deck[i_P * (n_H + 1) - 1]</code>. All players combined always hold less than <code>n_C</code> cards.</p>
  
  <p>Now I want to sort each player's hand, but not the entire deck (obviously, as this would move some cards between players' hands). I've gone about this like so:</p>
  
  <pre><code>void sort_hands(char * deck, size_t n_P) {
      for (size_t i_P = 0; i_P &lt; n_P; i_P++)
          sort_cards(deck + i_P * n_H, n_H);
  }
  </code></pre>
  
  <p>And then, using insertion sort (this function will sort an entire array just fine):</p>
  
  <pre><code>void sort_cards(char * cards, size_t n) {
      for (size_t i = 0; i &lt; n; i++) {
          for (size_t j = i - 1; j &gt;= 0; j--) {
              if (cards[j] &gt; cards[j + 1])
                  card_swap(cards, j, j + 1);
              else
                  break;
      }
  }
  </code></pre>
  
  <p>*Note: <code>card_swap</code>does  exactly what you would expect it to, it's only 3 statements.</p>
  
  <p>Both <code>n_C</code>and <code>n_H</code> are <code>#define</code>'d constants, <code>n_P</code> is a local variable.
  When I run the above code with a shuffled deck, and params <code>n_C = 104, n_H = 10, n_P = 3</code>, I get:</p>
  
  <p>0: <code>74 31 53 46 42 75 72 77 70 49</code></p>
  
  <p>1: <code>76 86 99 78 11 94 61 14 41 87</code></p>
  
  <p>2: <code>40 26 92 5 9 3 66 63 101 98</code></p>
  
  <p>before subarray sorting and something like:</p>
  
  <p>0: <code>3 5 9 11 31 42 46 49 53 74</code></p>
  
  <p>1: <code>61 70 75 72 76 77 78 86 94 99</code></p>
  
  <p>2: <code>14 26 40 41 63 66 87 92 98 101</code></p>
  
  <p>afterwards. As we can see, some cards have moved hands when they shouldn't have. But the deck has not been sorted across all hands (see e.g. <code>14</code> in player 2's hand. How can this be? The way I see it, my coding skills are not at fault, but the compiler seems to be messing with me.</p>
  
  <p>I have observed this behaviour both with the VS15 C++ compiler as well as GCC.</p>