let pancake_sort xs =
  let a = Array.of_list xs in
  let n = Array.length a in
  let flips = ref 0 in
  let flip k =
    let lo = ref 0 and hi = ref k in
    while !lo < !hi do
      let tmp = a.(!lo) in
      a.(!lo) <- a.(!hi);
      a.(!hi) <- tmp;
      lo := !lo + 1;
      hi := !hi - 1
    done;
    flips := !flips + 1
  in
  let find_max k =
    let m = ref 0 in
    for i = 1 to k do
      if a.(i) > a.(!m) then m := i
    done;
    !m
  in
  for size = n downto 2 do
    let mi = find_max (size - 1) in
    if mi <> size - 1 then begin
      if mi > 0 then flip mi;
      flip (size - 1)
    end
  done;
  !flips * 100 + a.(0) + a.(n - 1)
;;

pancake_sort [3; 1; 4; 1; 5; 9; 2; 6]
