When switch is at position 1, C is connected in series with $E_1\; and\; E_2$

By KVL

$Q_i= C( E_2 -E_1)$

When switch is moved to position 2, $Q_f= -E_1C$

$\Delta Q= Q_f -Q_i =-C E_2$

Net +ve charge pulled by battery $(E_1)= CE_2$

Work done in process of charge transfer $=CE_1E_2=\Delta w$

Change in energy of the capacitance

$ \Delta W_c=\large\frac{q_f^2}{2C} -\frac{Q_i ^2}{2C}$

$\qquad= \large\frac{1}{2}$$ E_1^2 C -\large\frac{1}{2}$$ (E^2-E_1)^2 C$

$\qquad= \large\frac{1}{2} $$(2 E_1 E_2-E_2^2)C$

Remaining part is lost as heat

$H= \Delta W- \Delta W_c$

$\quad= \large\frac{1}{2} {E_2}^2 C$

Hence B is the correct answer.