Advertisement
Guest User

Untitled

a guest
Oct 8th, 2017
65
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
D 1.49 KB | None | 0 0
  1.     public inline function insert(obj:T) {
  2.         assert(!has(obj),"object already in set");
  3.  
  4.         //ROTATE(x,left,right) = left rotation
  5.         //ROTATE(x,right,left) = right rotation
  6.         $(mixin ROTATE(x,L,R) {
  7.             var y = x.R;
  8.             x.R = y.L;
  9.             if(y.L!=null) y.L.parent = x;
  10.             y.parent = x.parent;
  11.             if(x.parent==null) parent = y; //root
  12.             elif(x==x.parent.L) x.parent.L = y;
  13.             else                x.parent.R = y;
  14.             y.L = x;
  15.             x.parent = y;
  16.         });
  17.  
  18.         var x = Get(Set(T));
  19.         x.data = obj;
  20.  
  21.         __insert(x);
  22.  
  23.         //rebalancing tree and satisfaction of red-black properties
  24.         while(x!=parent/*root*/ && x.parent.isred) {
  25.             var g = x.parent.parent;
  26.             $(mixin IF(L,R) {
  27.                 var y = g.R;
  28.                 if(y!=null && y.isred) {
  29.                     x.parent.isred = y.isred = false;
  30.                     g.isred = true;
  31.                     x = g;
  32.                 }else {
  33.                     if(x==x.parent.R) {
  34.                         x = x.parent;
  35.                         ROTATE(x,L,R);
  36.                     }
  37.                     x.parent.isred = false;
  38.                     g = x.parent.parent;
  39.                     g.isred = true;
  40.                     ROTATE(g,R,L);
  41.                 }
  42.             });
  43.             if(x.parent==g.prev) IF(prev,next) else IF(next,prev);
  44.         }
  45.         parent.isred = false; //root
  46.     }
  47.  
  48.     inline function __insert(n:Set(T)) {
  49.         n.isred = true;
  50.  
  51.         if(parent==null) parent = n; //roots
  52.         else {
  53.             var cur = parent; //root
  54.             while(true) {
  55.                 if(n.data.rb_lt(cur.data)) {
  56.                     if(cur.prev==null) { cur.prev = n; n.parent = cur; break; }
  57.                     else cur = cur.prev;
  58.                 }else {
  59.                     if(cur.next==null) { cur.next = n; n.parent = cur; break; }
  60.                     else cur = cur.next;
  61.                 }
  62.             }
  63.         }
  64.         return n;
  65.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement