UP | HOME
Land of Lisp

Zhao Wei

How can man die better than facing fearful odds, for the ashes of his fathers and the temples of his Gods? -- By Horatius.

OCaml Cheatsheet

1. Imperative Programming

1.1. Quicksort   array

let myarr = [|3;2;1;4;5|];;

let swap myarr i j =
  let tmp = myarr.(i) in
  myarr.(i) <- myarr.(j);
  myarr.(j) <- tmp;;


let partition myarr p r =
  let x = myarr.(r) in
  let i = ref (p-1) in
  for j =p to r-1 do
    if myarr.(j) < x then
      (
	i := !i + 1;
	swap myarr !i j;           
      )
  done;
  i := !i + 1;
  swap myarr !i r;
  i;;

let rec qsort_aux myarr p r =
  if p < r then
    (
      let m = partition myarr p r in
      qsort_aux myarr p (!m-1);
      qsort_aux myarr (!m+1) r;
    );;

let qsort myarr =
  qsort_aux myarr 0 ((Array.length myarr)-1);
  myarr;;

let myarr = [|1;3;5;4;2|];;
qsort myarr;;