Finding optimal separating value
Initialize an array of pairs $T[i] = (x, c)$ containing all elements of $A$ and $B$. Let $x$ be the elements themselves, and $c = 0$ if the element came from $A$ and $c = 1$ if the element came from $B$. Then sort $T$ based on the $x$ values in ascending order.
Then the number of mistakes you'd get if you choose a value between $T[i]\text{.}x$ and $T[i+1]\text{.}x$ is:
$$\sum_{j=0}^i T[j]\text{.}c + \sum_{j=i+1}^n\left(1 - T[j]\text{.}c\right) = $$
$$(n - i) +\sum_{j=0}^i T[j]\text{.}c - \sum_{j=i+1}^nT[j]\text{.}c = $$
$$(n - i) +2\sum_{j=0}^i T[j]\text{.}c - \sum_{j=0}^nT[j]\text{.}c = $$
$$- i +2\sum_{j=0}^i T[j]\text{.}c - C$$
where $C$ is just a constant, which doesn't matter if you wish to minimize the quantity. So to find the optimal value:
S = 0
best = inf
best_i = 1
for 1 &lt;= i &lt;= n:
    S += 2*T[i].c
    if S - i &lt; best:
        best = S - i
        best_i = i