This implementation of merge sort throws an out of bounds exception, because it attempt to access A[i] (in case 1) before checking i==m (in case 2). Here's the fixed version: int Apos = 0, Bpos = 0; for (int i = 0; i < C.size(); i++) { if (Apos == A.size() || ((Bpos < B.size()) && (B[Bpos]