image thumbnail
from Order book simulation by Dimitri Shvorob
(a naive artificial stock market)

PriorityQueue
classdef PriorityQueue < Queue
           
   properties (SetAccess = private)
       Comparator       
   end
   
   methods
          
       function[obj] = PriorityQueue(comparator)
           obj.Comparator = comparator;       
       end
       
       function put(obj,val)
           if isempty(obj)
              obj.Values = val;
           else
              n = length(obj.Values);
              r = n + 1;    % prospective rank of new entry          
              for i = 1:n
                  r = r - obj.Comparator(val,obj.Values(i));
              end  
              if r == n + 1
                 obj.Values(end+1) = val;
              elseif r == 1
                 obj.Values = [val obj.Values];
              else
                 obj.Values = [obj.Values(1:r-1) val obj.Values(r:end)];
              end
           end   
       end   
                  
   end   
    
end

Contact us at files@mathworks.com