In[]:=
HeapSortingAlgorithm
Out[]=
AlgorithmHeapSorting
In[]:=
heapbottompointer=1;heaptoppointer=2.;makeHeap[len_]:=Table[0.,{len+1}]
In[]:=
SetAttributes[addToHeap,HoldFirst];addToHeap[heap_,elem_Real]:=Module[{j1,j2},heap[[heapbottompointer]]+=1;j1=heap[[heapbottompointer]];heap[[j1+1]]=elem;While[(j2=Floor[j1/2])≥1&&heap[[j2+1]]>heap[[j1+1]],heap[[{j1+1,j2+1}]]=heap[[{j2+1,j1+1}]];j1=j2;];]
In[]:=
SetAttributes[removeFromHeap,HoldFirst];removeFromHeap[heap_]:=Module[{prev=2,j1=2,j2=3,top=heap[[heaptoppointer]],last,next},last=heap[[heapbottompointer]];While[j1<=last,If[j2≤last,next=If[heap[[j1+1]]≤heap[[j2+1]],j1,j2],next=j1];heap[[prev]]=heap[[next+1]];prev=next+1;{j1,j2}=2*next+{0,1};];heap[[heapbottompointer]]-=1;heap[[prev]]=heap[[last+1]];j1=prev-1;While[(j2=Floor[j1/2])≥1&&heap[[j2+1]]>heap[[j1+1]],heap[[{j1+1,j2+1}]]=heap[[{j2+1,j1+1}]];j1=j2;];top]
In[]:=
heapSort[ll_]:=Module[{len=Length[ll],heap,res,j1,j2},heap=makeHeap[len];Map[addToHeap[heap,#]&,ll];res=Table[removeFromHeap[heap],{len}];res]
In[]:=
heapSortPrepareC=Compile[{{ll,_Real,1}},Module[{len=Length[ll],heap,res,j1,j2},heap=Table[0.,{len+1}];Do[heap[[1]]+=1.;j1=Round[heap[[1]]];heap[[j1+1]]=ll[[j]];While[(j2=Floor[j1/2])≥1&&heap[[j2+1]]>heap[[j1+1]],heap[[{j1+1,j2+1}]]=heap[[{j2+1,j1+1}]];j1=j2;];,{j,len}];heap]];
In[]:=
heapEmptyC=Compile[{{oheap,_Real,1}},Module[{heap=oheap,prev,j1,j2,top,last,next,len},len=Length[heap]-1;Table[last=Round[heap[[1]]];top=heap[[2]];prev=2;j1=2;j2=3;While[j1<=last,If[j2≤last,next=If[heap[[j1+1]]≤heap[[j2+1]],j1,j2],next=j1];heap[[prev]]=heap[[next+1]];prev=next+1;{j1,j2}=2*next+{0,1};];heap[[1]]-=1.;heap[[prev]]=heap[[last+1]];j1=prev-1;While[(j2=Floor[j1/2])≥1&&heap[[j2+1]]>heap[[j1+1]],heap[[{j1+1,j2+1}]]=heap[[{j2+1,j1+1}]];j1=j2;];top,{len}]]];
In[]:=
heapSortC[ll_]:=Module[{len=Length[ll],heap,res,j1,j2},heap=heapSortPrepareC[ll];res=heapEmptyC[heap];res]
In[]:=
FastMarchingAlgorithm
Out[]=
AlgorithmFastMarching
In[]:=
frozen=-1.;far=300.;band=0.;outofbounds=1000.;nostate=1000;maxPixelValue=255.;minPixelValue=0.;midPixelValue=(maxPixelValue-minPixelValue)/2;
In[]:=
Attributes[state]=HoldFirst;state[states_,x_,y_]:=If[x>Length[states]||x<1||y>Length[states[[x]]]||y<1,1000,states[[x,y]]];
In[]:=
Attributes[distance]=HoldFirst;distance[distances_,x_,y_]:=If[x>Length[distances]||x<1||y>Length[distances[[x]]]||y<1,1000.,distances[[x,y]]];
In[]:=
neighborValue[l1_,l2_,states_,distances_]:=Module[{s1=state[states,Apply[Sequence,l1]],s2=state[states,Apply[Sequence,l2]]},Which[s1≠frozen&&s2≠frozen,outofbounds,s1frozen&&s2frozen,Min[distance[distances,Apply[Sequence,l1]],distance[distances,Apply[Sequence,l2]]],s1frozen,distance[distances,Apply[Sequence,l1]],s2frozen,distance[distances,Apply[Sequence,l2]]]]