Exemple #1
0
void RBtree<Key,Value,Compare>::add(Key k,Value v)
{
	Compare comp; //obiekt porównujący
	Node* newone;
	newone = new Node(k,v); //z
	Node* y; //y
	Node* x; //x
	y = sentinel;
	x = root;
	while (x != sentinel)
	{
		y = x;
		if ( comp.less(newone->k,x->k) )
			x = x->left;
		else
			x = x->right;
	}
	newone->parrent = y;
	if (y == sentinel)
		root = newone;
	else
		if ( comp.less(newone->k,y->k) )
			y->left = newone;
		else
			y->right = newone;
	newone->left = sentinel;
	newone->right = sentinel;
	newone->color = RED;
	RBfix(newone);
}
I upper_bound(I first, I end, Compare& c, const Key& k) {
    I last = end; --last;
    //if (c.less(k, *first)) return first;
    if (c.less(*last, k)) return end;
    int step;
    int count = end - first;
    I it;
    while (count>0) {
        it = first; step=count/2; it += step;
        if (!c.less(k, *it)) {
            first=++it; count-=step+1;
        }
        else count=step;
    }
    return first;
}
I search(I first, I end, Compare& c, const Key& k) {
    I last = end; --last;
    if (c.less(k, *first) || c.less(*last, k)) return end;
    if (c.equal(k, *first)) return first;
    if (c.equal(k, *last)) return last;
    while (true) {
        int diff = last - first;
        if (diff <= 1)
            return end;
        I middle = first+diff/2;
        if (c.less(k, *middle))
            last = middle;
        else if (c.less(*middle, k))
            first = middle;
        else
            return middle;
    }
}
void sort(I first, I last, Compare& c, uint64_t bytes) {
    char* tmp = new char[bytes];
    while (last != first) {
        I cur = first;
        while (cur != last) {
            I next = cur+1;
            if (c.less(*(next), *cur)) {
                //std::cout << "Swapping values\n";
                std::memcpy(tmp, *cur, bytes);
                std::memcpy(*cur, *(cur+1), bytes);
                std::memcpy(*(cur+1), tmp, bytes);
                //std::cout << "Swapped values\n";
                //std::swap_ranges(*cur, *(cur+1), *(cur+1));
            }
            ++cur;
        }
        --last;
    }
    delete[] tmp;
}