let kth_two a b k =
  let m = Array.length a in
  let n = Array.length b in
  let i = ref 0 and j = ref 0 and count = ref 0 in
  let result = ref 0 in
  while !count < k do
    let pick_a =
      if !i = m then false
      else if !j = n then true
      else a.(!i) <= b.(!j)
    in
    if pick_a then begin
      result := a.(!i);
      i := !i + 1
    end else begin
      result := b.(!j);
      j := !j + 1
    end;
    count := !count + 1
  done;
  !result

;;

let a = [| 1; 3; 5; 7; 9; 11; 13 |] in
let b = [| 2; 4; 6; 8; 10; 12 |] in
kth_two a b 8
