To handle 2 elements
if ( high - low <= 1 ) { if ( a [ high ] < a [ low ] ) swap ( & a [ high ] , & a [ low ] ) ; i = low ; j = high ; return ; } int mid = low ; int pivot = a [ high ] ; while ( mid <= high ) { if ( a [ mid ] < pivot ) swap ( & a [ low ++ ] , & a [ mid ++ ] ) ; else if ( a [ mid ] == pivot ) mid ++ ; else if ( a [ mid ] > pivot ) swap ( & a [ mid ] , & a [ high -- ] ) ; }