123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117(**************************************************************************)(* *)(* Ocamlgraph: a generic graph library for OCaml *)(* Copyright (C) 2004-2010 *)(* Sylvain Conchon, Jean-Christophe Filliatre and Julien Signoles *)(* *)(* This software is free software; you can redistribute it and/or *)(* modify it under the terms of the GNU Library General Public *)(* License version 2.1, with the special exception on linking *)(* described in file LICENSE. *)(* *)(* This software is distributed in the hope that it will be useful, *)(* but WITHOUT ANY WARRANTY; without even the implied warranty of *)(* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. *)(* *)(**************************************************************************)moduletypeOrdered=sigtypetvalcompare:t->t->intendexceptionEmptyHeapmoduleImperative(X:Ordered)=struct(* The heap is encoded in the array [data], where elements are stored
from [0] to [size - 1]. From an element stored at [i], the left
(resp. right) subtree, if any, is rooted at [2*i+1] (resp. [2*i+2]). *)typet={mutablesize:int;mutabledata:X.tarray}(* When [create n] is called, we cannot allocate the array, since there is
no known value of type [X.t]; we'll wait for the first addition to
do it, and we remember this situation with a negative size. *)letcreaten=ifn<=0theninvalid_arg"create";{size=-n;data=[||]}letis_emptyh=h.size<=0(* [resize] doubles the size of [data] *)letresizeh=letn=h.sizeinassert(n>0);letn'=2*ninletd=h.datainletd'=Array.maken'd.(0)inArray.blitd0d'0n;h.data<-d'letaddhx=(* first addition: we allocate the array *)ifh.size<0thenbeginh.data<-Array.make(-h.size)x;h.size<-0end;letn=h.sizein(* resizing if needed *)ifn==Array.lengthh.datathenresizeh;letd=h.datain(* moving [x] up in the heap *)letrecmoveupi=letfi=(i-1)/2inifi>0&&X.compared.(fi)x<0thenbegind.(i)<-d.(fi);moveupfiendelsed.(i)<-xinmoveupn;h.size<-n+1letmaximumh=ifh.size<=0thenraiseEmptyHeap;h.data.(0)letremoveh=ifh.size<=0thenraiseEmptyHeap;letn=h.size-1inh.size<-n;letd=h.datainletx=d.(n)in(* moving [x] down in the heap *)letrecmovedowni=letj=2*i+1inifj<nthenletj=letj'=j+1inifj'<n&&X.compared.(j')d.(j)>0thenj'elsejinifX.compared.(j)x>0thenbegind.(i)<-d.(j);movedownjendelsed.(i)<-xelsed.(i)<-xinmovedown0letpop_maximumh=letm=maximumhinremoveh;mletiterfh=letd=h.datainfori=0toh.size-1dofd.(i)doneletfoldfhx0=letn=h.sizeinletd=h.datainletrecfoldrecxi=ifi>=nthenxelsefoldrec(fd.(i)x)(succi)infoldrecx00end