Algorithms & Data structures in C++.

Algorithms & Data Structures in C++

Build Status

目标 ( goal ) :

  1. 经典的算法实现
    (classical algorithms implementations)
  2. 服务器端
    (based on linux/gcc)
  3. 正确,易于使用和改造, 一个头文件一个算法,并附带一个demo.
    (correct! and ease of use, one .header file per algorithm)

约定 ( Convention ):

  1. 一个算法用一个.h文件表示放到include下. ( one .header file per algorithm. )
  2. 算法演示的demo程序放到src下. ( one demo per algorithm. )
  3. 程序正确通过后,请发起Pull Requests,代码被验证后入库,并在README中发布新算法实现。 (Please Use Fork+Pull Requests !!! Correctness is the most important!)
  4. TAB = 4 space. set ts=4 in vim
  5. Graph的输出格式为 Graphviz Dot格式. (the output format of the graph is in dot of graphviz.) eg: demograph

已实现 ( Implemented ):

Name File
Array shuffle https://github.com/xtaci/algorithms/blob/master/include/shuffle.h
Prime test(trial division) https://github.com/xtaci/algorithms/blob/master/include/prime.h
Prime test(Miller-Rabin's method) https://github.com/xtaci/algorithms/blob/master/include/prime.h
2D Array https://github.com/xtaci/algorithms/blob/master/include/2darray.h
Arbitrary Integer https://github.com/xtaci/algorithms/blob/master/include/integer.h
Linear congruential generator https://github.com/xtaci/algorithms/blob/master/include/random.h
Maximum subarray problem https://github.com/xtaci/algorithms/blob/master/include/max_subarray.h
Bit-Set https://github.com/xtaci/algorithms/blob/master/include/bitset.h
Queue https://github.com/xtaci/algorithms/blob/master/include/queue.h
Stack https://github.com/xtaci/algorithms/blob/master/include/stack.h
Binary Heap https://github.com/xtaci/algorithms/blob/master/include/heap.h
Fibonacci Heap https://github.com/xtaci/algorithms/blob/master/include/fib-heap.h
Priority Queue (list based) https://github.com/xtaci/algorithms/blob/master/include/priority_queue.h
Bubble sort https://github.com/xtaci/algorithms/blob/master/include/bubble_sort.h
Selection sort https://github.com/xtaci/algorithms/blob/master/include/selection_sort.h
Insertion sort https://github.com/xtaci/algorithms/blob/master/include/insertion_sort.h
Shell sort https://github.com/xtaci/algorithms/blob/master/include/shell_sort.h
Radix sort https://github.com/xtaci/algorithms/blob/master/include/radix_sort.h
Quicksort https://github.com/xtaci/algorithms/blob/master/include/quick_sort.h
Merge sort https://github.com/xtaci/algorithms/blob/master/include/merge_sort.h
Double linked list https://github.com/xtaci/algorithms/blob/master/include/double_linked_list.h
Skip list https://github.com/xtaci/algorithms/blob/master/include/skiplist.h
Largest common sequence https://github.com/xtaci/algorithms/blob/master/include/lcs.h
Binary search tree https://github.com/xtaci/algorithms/blob/master/include/binary_search_tree.h
AVL tree https://github.com/xtaci/algorithms/blob/master/include/avl.h
Dynamic order statistics https://github.com/xtaci/algorithms/blob/master/include/dos_tree.h
Red-black tree https://github.com/xtaci/algorithms/blob/master/include/rbtree.h
Interval tree https://github.com/xtaci/algorithms/blob/master/include/interval_tree.h
Prefix Tree(Trie) https://github.com/xtaci/algorithms/blob/master/include/trie.h
Suffix Tree https://github.com/xtaci/algorithms/blob/master/include/suffix_tree.h
B-Tree https://github.com/xtaci/algorithms/blob/master/include/btree.h
Suffix Array https://github.com/xtaci/algorithms/blob/master/include/suffix_array.h
Hash by multiplication https://github.com/xtaci/algorithms/blob/master/include/hash_multi.h
Hash table https://github.com/xtaci/algorithms/blob/master/include/hash_table.h
Universal hash function https://github.com/xtaci/algorithms/blob/master/include/universal_hash.h
Perfect hash https://github.com/xtaci/algorithms/blob/master/include/perfect_hash.h
Java's string hash https://github.com/xtaci/algorithms/blob/master/include/hash_string.h
FNV-1a string hash https://github.com/xtaci/algorithms/blob/master/include/hash_string.h
SimHash https://github.com/xtaci/algorithms/blob/master/include/simhash.h
Bloom Filter https://github.com/xtaci/algorithms/blob/master/include/bloom_filter.h
SHA-1 Message Digest Algorithm https://github.com/xtaci/algorithms/blob/master/include/sha1.h
MD5 https://github.com/xtaci/algorithms/blob/master/include/md5.h
Base64 https://github.com/xtaci/algorithms/blob/master/include/base64.h
Strongly Connected Components(SCC) https://github.com/xtaci/algorithms/blob/master/include/scc.h
Prim's minimum spanning tree https://github.com/xtaci/algorithms/blob/master/include/prim_mst.h
Kruskal MST https://github.com/xtaci/algorithms/blob/master/include/kruskal_mst.h
Breadth First Search https://github.com/xtaci/algorithms/blob/master/include/graph_search.h
Depth First Search https://github.com/xtaci/algorithms/blob/master/include/graph_search.h
Dijkstra's algorithm https://github.com/xtaci/algorithms/blob/master/include/dijkstra.h
Bellman-Ford algorithm https://github.com/xtaci/algorithms/blob/master/include/bellman_ford.h
Edmonds-Karp Maximal Flow https://github.com/xtaci/algorithms/blob/master/include/edmonds_karp.h
Push–Relabel algorithm https://github.com/xtaci/algorithms/blob/master/include/relabel_to_front.h
Huffman Coding https://github.com/xtaci/algorithms/blob/master/include/huffman.h
Word segementation https://github.com/xtaci/algorithms/blob/master/include/word_seg.h
A* algorithm https://github.com/xtaci/algorithms/blob/master/include/astar.h
K-Means https://github.com/xtaci/algorithms/blob/master/include/k-means.h
Knuth–Morris–Pratt algorithm https://github.com/xtaci/algorithms/blob/master/include/kmp.h
Disjoint-Set https://github.com/xtaci/algorithms/blob/master/include/disjoint-set.h
8-Queen Problem https://github.com/xtaci/algorithms/blob/master/include/8queen.h
Palindrome https://github.com/xtaci/algorithms/blob/master/include/palindrome.h
LCA using Binary Lifting https://github.com/xtaci/algorithms/blob/master/include/LCA.h

贡献者 ( Contributors ) :

Samana:  for heavy work of MSVC compatability
wycg1984: for K-Means
xmuliang: for HeapSort, Kruskal MST
wyh267: for base64, LRU, bubble sort, selection sort
ZhangYou0122: Push-Relabel algorithm, Suffix Tree           
UsingtcNower: Suffix Array
afernandez90: AVL trees

支持此项目 ( Donations ) :

donate
欢迎使用支付宝扫描上面的二维码,对该项目进行捐赠。捐赠款项将用于持续优化补全及完善。

Owner
xtaci
若人欲了知,三世一切佛,应观法界性,一切唯心造。
xtaci
Comments
  • Add Lowest common ancestor algorithm

    Add Lowest common ancestor algorithm

    In graph theory and computer science, the lowest common ancestor (LCA) of two nodes v and w in a tree or directed a cyclic graph (DAG) T is the lowest (i.e. deepest) node that has both v and w as descendants, where we define each node to be a descendant of itself (so if v has a direct connection from w, w is the lowest common ancestor).

    There's many methods to find the LCA, one can be using Euler tour and a segment tree or by using Binary lifting which is the implemented method.

  • 快速排序枢纽值pivot的选择不是最高效的.

    快速排序枢纽值pivot的选择不是最高效的.

    In https://github.com/xtaci/algorithms/blob/master/include/quick_sort.h

    在目前(2013年10月21日 16时12分55秒)快速排序算法的实现中,枢纽值pivot是通过随机数选取的,即int pivot_idx = RANDOM(begin,end);但这不是最高效的枢纽选择策略。 对快速排序效率影响最大的是枢纽值pivot的选择,建议采取首值、中间值和末尾值进行比较,选择中间大小的那个值作为枢纽值pivot策略。这样在数据量大的情况下,排序效果会更加高效。

    可以详见博客描述:http://blog.csdn.net/nwpu_kexie/article/details/7538673

  • fix bugs in base64.h

    fix bugs in base64.h

    INPUT: Man is distinguished not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure..

    encodeBase64: TWFuIGlzIGRpc3Rpbmd1aXNoZWQgbm90IG9ubHkgYnkgaGlzIHJlYXNvbiwgYnV0IGJ5IHRoaXMgc2luZ3VsYXIgcGFzc2lvbiBmcm9tIG90aGVyIGFuaW1hbHMsIHdoaWNoIGlzIGEgbHVzdCBvZiB0aGUgbWluZCwgdGhhdCBieSBhIHBlcnNldmVyYW5jZSBvZiBkZWxpZ2h0IGluIHRoZSBjb250aW51ZWQgYW5kIGluZGVmYXRpZ2FibGUgZ2VuZXJhdGlvbiBvZiBrbm93bGVkZ2UsIGV4Y2VlZHMgdGhlIHNob3J0IHZlaGVtZW5jZSBvZiBhbnkgY2FybmFsIHBsZWFzdXJlLi4=

    decodeBase64: Man is distinguished not only by his reason, but by this singular passion from other animals, which is a lust of the mind, that by a perseverance of delight in the continued and indefatigable generation of knowledge, exceeds the short vehemence of any carnal pleasure..

  • remove typeof from choose_pivot(...)

    remove typeof from choose_pivot(...)

    It's not making any sense to use typeof(i) to define length, since 'i' is obviously a 'int'. And it's probably not a good idea to put the choose pivot function in a separate file, this will force user to call srand() unnaturally.

  • Queue& needs to be const as well

    Queue& needs to be const as well

    https://github.com/xtaci/algorithms/blob/2ac19a715c06f2578c7ebbc201fff6c763320579/include/queue.h#L63

    You probably need to make the returned alias to be const as well. For info, check the (x = y) = z problem...

  • Segregated code

    Segregated code

    After looking at this project i want to say that this project is good for the one who is learning algorithm. The only opinion i could give right now is that if possible we could segregate the implementations in include directory( only contains the declarations ) and move it to .cpp file( some src directory). It not only helps in readability of the code but also the compile time could increase.

  • Conform to C++ standard

    Conform to C++ standard

    Hi, this is an awesome repository which contains a lot of useful algorithms for C++, but the code style, I think, could be improved:

    • Use <cstddef> instead of <stddef.h>
    • each identifier with two underscores at the beginning(__foobar) or one underscore followed by character in uppercase(_Foobar) is reserved by language
    • the void keyword could be omitted inint main(void), so is struct in struct Foo obj
  • Build error gcc (GCC) 6.1.1 20160501

    Build error gcc (GCC) 6.1.1 20160501

    Hello,

    first of all, this is a great compilation of non-trivial algorithms ... thank you for putting it together.

    secondly, I get this build error for suffix_tree in my environment. most probably compiler dependent issues. I will look into it and if i fix it I will send a pull request from a fork.

    In file included from src/suffix_tree_demo.cpp:1:0: ./include/suffix_tree.h: In member function ‘Iterator SuffixTree::inc_search(Iterator)’: ./include/suffix_tree.h:34:41: warning: typedef ‘T’ locally defined but not used [-Wunused-local-typedefs] typedef typename Iterator::value_type T; // extract real type ^ ./include/suffix_tree.h: In function ‘std::ostream& operator<<(std::ostream&, SuffixTree::Node&)’: ./include/suffix_tree.h:214:8: error: ‘typedef struct SuffixTree::Edge SuffixTree::Edge’ is private within this context map<Edge*, bool>::iterator iter; ^~~~ ./include/suffix_tree.h:149:22: note: declared private here typedef struct Edge Edge; ^~~~ ./include/suffix_tree.h:215:14: error: ‘typedef struct SuffixTree::Edge SuffixTree::Edge’ is private within this context map<char, Edge*>::iterator iter_f; ^~~~ ./include/suffix_tree.h:149:22: note: declared private here typedef struct Edge Edge; ^~~~ src/suffix_tree_demo.cpp: At global scope: src/suffix_tree_demo.cpp:107:70: error: no ‘SuffixTree::Node* SuffixTree::seperate_edge(SuffixTree::Node_, SuffixTree::Edge_)’ member function declared in class ‘SuffixTree’ SuffixTree::Node* SuffixTree::seperate_edge(Node * node, Edge* a_edge) ^ src/suffix_tree_demo.cpp:107:13: error: ‘typedef struct SuffixTree::Node SuffixTree::Node’ is private within this context SuffixTree::Node* SuffixTree::seperate_edge(Node * node, Edge* a_edge) ^~~~ In file included from src/suffix_tree_demo.cpp:1:0: ./include/suffix_tree.h:81:22: note: declared private here typedef struct Node Node; ^~~~ src/suffix_tree_demo.cpp:107:58: error: ‘typedef struct SuffixTree::Edge SuffixTree::Edge’ is private within this context SuffixTree::Node* SuffixTree::seperate_edge(Node * node, Edge* a_edge) ^~~~ In file included from src/suffix_tree_demo.cpp:1:0: ./include/suffix_tree.h:149:22: note: declared private here typedef struct Edge Edge; ^~~~ Makefile:257: recipe for target 'suffix_tree_demo' failed make: *** [suffix_tree_demo] Error 1

  • AVL Trees added

    AVL Trees added

    Hi, I added a generic AVL tree. I saw there is already an RBTree structure in the repo and uses key/value pairs. In my case, I think AVL trees are not only for dictionaries with key/value pairs. However, the same behavior can be achieved by making the elements in the AVL a key/value pair and redefining the ordering operators, just like when using an std::set.

    The AVL is more balanced than a RBT but it takes a bit longer to insert/delete elements due to the rotations. So it's faster for searching but slower for the rest.

  • Swapped indexes in astar.h

    Swapped indexes in astar.h

    Hey man, while using your fantastic rep I encountered a bug in the astar header, in particular the indexing of the grid in the neighbor search when using nx,ny and cx,cy where swapped. That was causing the algorithm to search blocks that could be occupied by walls if the map was different from the sample one. I'm using your astar header in one of my repositories, so if you want feel free to have a look at the changes I've done :wink:

    I'm not using the github tools to fork the rep and request a merge since I'm somehow new to git and I don't want to create a mess :tongue:

  • LRU算法链表名称问题

    LRU算法链表名称问题

    个人觉得链表的头和尾p_cache_list_head, p_cache_list_near 用类似p_cache_list_head, p_cache_list_tail 或者 p_cache_list_front, p_cache_list_rear感觉更好些 p_cache_list_near的意思读起来不是很清晰

  • double linked list demo 失败

    double linked list demo 失败

    hi,各位: 我的代码环境:g++ 4.8.4, Ubuntu 14.04.6,kernel 4.4.0-148-generic 失败的地方是在 src/double_linked_list_demo.cpp 中的代码:

    	list_for_each_prev(pos, &head){
    		struct DemoNode * node = list_entry(pos, struct DemoNode, list);
    		printf("%d\n", node->key);
    	}
    	
    	list_for_each_entry(node, &head, list){
    		printf("%d\n", node->key);
    	}
    

    上面demo 示例,list_for_each_prev 中,list_entry中的type 参数是struct DemoNode, 但在 list_for_each_entry 中使用 typeof(*pos) (也就是decltype(*pos) ) , 它返回的type 为 struct DemoNode& , 也就导致编译失败。我做了下面的简单修复.

    其中原来的 list_for_each_entry 的实现

    
    #ifndef _MSC_VER
    #define list_for_each_entry(pos, head, member)				\
    	for (pos = list_entry((head)->next, typeof(*pos), member);	\
    	     &pos->member != (head); 					\
    	     pos = list_entry(pos->member.next, typeof(*pos), member))
    #else
    #define list_for_each_entry(pos, head, member)				\
    	for (pos = list_entry((head)->next, typeof(pos), member);	\
    	     &pos->member != (head); 					\
    	     pos = list_entry(pos->member.next, typeof(pos), member))
    #endif
    

    修复:

    
    #define list_for_each_entry(pos, head, member)               \
      for (pos = list_entry_ptr((head)->next, typeof(pos), member); \
           &pos->member != (head);                               \
           pos = list_entry_ptr(pos->member.next, typeof(pos), member))
    
    #define list_entry_ptr(ptr, ptrtype, member) \
      (reinterpret_cast<ptrtype>(            \
          (char *)(ptr) - (char *)(&(reinterpret_cast<ptrtype>(1)->member)) + 1))
    
    
Several algorithms and data structures implemented in C++ by me (credited to others where necessary).

Algorithms This repository contains my implementations of several algorithms and data structures in C++ (credited to others where necessary). It has i

Dec 19, 2022
Collection of algorithms and data structures in C++ and Java

Collection of algorithms and data structures in C++ and Java

Jan 2, 2023
Fundamentals of Data structures and algorithms in c++
Fundamentals of Data structures and algorithms in c++

Data Structures & Algorithms About the repository: Contains theories and programming questions related to fundamentals of data structures and algorith

Dec 1, 2022
C++17 (-O2) template for competitive programming algorithms, which contains numerous math algorithms.

cpplibForCP C++17 (-O2) template for competitive programming algorithms, which contains numerous math algorithms. Aims: build a stable, fast, easy-to-

Nov 25, 2022
Collection of various algorithms in mathematics, machine learning, computer science, physics, etc implemented in C for educational purposes.

The Algorithms - C # {#mainpage} Overview The repository is a collection of open-source implementation of a variety of algorithms implemented in C and

Jan 5, 2023
C++ implementations of well-known (and some rare) algorithms, while following good software development practices

ProAlgos: C++ This project is focused on implementing algorithms and data structures in C++, while following good software engineering practices, such

Dec 7, 2022
This repository contains path planning algorithms in C++ for a grid based search.

This repository contains path planning algorithms in C++ for a grid based search.

Dec 30, 2022
Provide building blocks (software, hardware and algorithms) for implementing SLAM using small sensors
Provide  building blocks (software, hardware and algorithms) for implementing SLAM using small sensors

RemoteSLAM The purpose of this repo is to provide the building blocks (software drivers, hardware and algorithms) for implementing SLAM systems using

Jan 20, 2022
CXXGraph is a Header-Only C++ Library for Graph Representation and Algorithms
CXXGraph is a Header-Only C++ Library for Graph Representation and Algorithms

CXXGraph is a small library, header only, that manages the Graph and it's algorithms in C++. In other words a "Comprehensive C++ Graph Library".

Dec 29, 2022
Library for building multi-level indoor routes using routing algorithms.

Library for building multi-level indoor routes using routing algorithms. You can easily construct routing graphs and find the shortest path for optimal indoor navigation.

Nov 21, 2022
Header-only C++ library for robotics, control, and path planning algorithms.
Header-only C++ library for robotics, control, and path planning algorithms.

Header-only C++ library for robotics, control, and path planning algorithms.

Dec 13, 2022
c++ library including few algorithms and datastructures

c++ library including few algorithms and datastructures

Dec 25, 2021
This library contains a set of algorithms for working with the routing graph.

Library for building multi-level indoor routes using routing algorithms. You can easily construct routing graphs and find the shortest path for optimal indoor navigation.

Nov 21, 2022
IntX is a C++11 port of IntX arbitrary precision Integer library with speed, about O(N * log N) multiplication/division algorithms implementation.

IntX IntX is a C++11 port of IntX arbitrary precision Integer library with speed, about O(N * log N) multiplication/division algorithms implementation

Dec 22, 2022
In this project, we implemented twelve different sorting algorithms.

C - Sorting algorithms & Big O In this project, we implemented twelve different sorting algorithms. Tests tests: Folder of test files. Provided by Alx

Oct 26, 2021
All basic algorithms for solving problems of CP

All basic algorithms for solving problems of CP

Nov 14, 2021
Every week exercises for Introduction to Algorithms and Programming

cen109-algorithms commands to compile and link C and C++ programs gcc filename.c -o executableFileName g++ filename.cpp -o executableFileName filename

Dec 19, 2022
c language's datastruct and algorithms.

cdsaa 介绍 学习数据结构与算法的C语言实现 主要数据结构 动态字符串 动态数组 单向链表 栈 主要算法 更新中. . . 目录结构 |-- include |---- CArray.h 动态数组 |---- CList.h 单向链表 |---- CStack.h 栈 |---- CString

Nov 24, 2021
Sorting algorithms & Big O

[![Contributors][contributors-shield]][contributors-url] [![Forks][forks-shield]][forks-url] [![Stargazers][stars-shield]][stars-url] Sorting algorith

Nov 7, 2021