Algorithms_in_C++ 1.0.0
Set of algorithms implemented in C++.
Loading...
Searching...
No Matches
treap.cpp File Reference

A balanced binary search tree (BST) on the basis of binary search tree and heap: the Treap algorithm implementation. More...

#include <array>
#include <cassert>
#include <iostream>
Include dependency graph for treap.cpp:

Classes

struct  data_structures::treap::Treap
 Struct representation of the treap. More...
 

Namespaces

namespace  data_structures
 for IO operations
 

Functions

static void test ()
 Self-test implementations.
 
int main ()
 Main function.
 

Variables

const int data_structures::treap::maxNode = 1e5 + 5
 maximum number of nodes
 

Detailed Description

A balanced binary search tree (BST) on the basis of binary search tree and heap: the Treap algorithm implementation.

Implementation of the treap data structre

Support operations including insert, erase, and query (the rank of specified element or the element ranked x) as the same as BST

But these operations take O(log N) time, since treap keeps property of heap using rotate operation, and the desired depth of the tree is O(log N). There's very little chance that it will degenerate into a chain like BST

Author
Kairao ZHENG

Function Documentation

◆ main()

int main ( void )

Main function.

Returns
0 on exit
256 {
257 test(); // run self-test implementations
258 return 0;
259}
static void test()
Self-test implementations.
Definition treap.cpp:230
Here is the call graph for this function:

◆ test()

static void test ( )
static

Self-test implementations.

Returns
void

< Treap object instance

230 {
231 data_structures::treap::Treap mTreap; ///< Treap object instance
232
233 mTreap.insert(1);
234 mTreap.insert(2);
235 mTreap.insert(3);
236 assert(mTreap.get_k_th(2) == 2);
237 mTreap.insert(4);
238 mTreap.insert(5);
239 mTreap.insert(6);
240 assert(mTreap.get_next(4) == 5);
241 mTreap.insert(7);
242 assert(mTreap.get_predecessor(7) == 6);
243 mTreap.erase(4);
244 assert(mTreap.get_k_th(4) == 5);
245 assert(mTreap.get_rank(5) == 4);
246 mTreap.insert(10);
247 assert(mTreap.get_rank(10) == 7);
248 assert(mTreap.get_predecessor(10) == 7);
249
250 std::cout << "All tests have successfully passed!\n";
251}
Struct representation of the treap.
Definition treap.cpp:39
void insert(int k)
Insert element (External method)
Definition treap.cpp:204
int get_next(int k)
Get the successor node of element k.
Definition treap.cpp:189
void erase(int k)
Erase element (External method)
Definition treap.cpp:209
int get_k_th(int k)
Get the KTH largest value (External method)
Definition treap.cpp:215
int get_predecessor(int k)
Get the predecessor node of element k.
Definition treap.cpp:173
int get_rank(int k)
Get the rank of specified element (External method)
Definition treap.cpp:221
Here is the call graph for this function: