Convert Figma logo to code with AI

TheAlgorithms logoC-Plus-Plus

Collection of various algorithms in mathematics, machine learning, computer science and physics implemented in C++ for educational purposes.

30,039
7,101
30,039
17

Top Related Projects

183,979

All Algorithms implemented in Python

58,536

All Algorithms implemented in Java

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings

Minimal examples of data structures and algorithms in Python

120+ interactive Python coding interview challenges (algorithms and data structures). Includes Anki flashcards.

:fireworks:Interactive Online Platform that Visualizes Algorithms from Code

Quick Overview

TheAlgorithms/C-Plus-Plus is a comprehensive collection of various algorithms and data structures implemented in C++. It serves as an educational resource for students, developers, and enthusiasts to learn and understand different algorithmic concepts through practical implementations.

Pros

  • Extensive collection of algorithms covering various domains such as sorting, searching, graph theory, and more
  • Well-organized directory structure, making it easy to navigate and find specific algorithms
  • Implementations are generally clear and well-commented, aiding in understanding
  • Active community contributing to and maintaining the repository

Cons

  • Some implementations may not be optimized for production use
  • Inconsistent coding style across different contributions
  • Limited documentation for some algorithms, which may make it challenging for beginners
  • Some implementations may not follow modern C++ best practices

Code Examples

  1. Binary Search implementation:
int binarySearch(int arr[], int l, int r, int x) {
    if (r >= l) {
        int mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return binarySearch(arr, l, mid - 1, x);
        return binarySearch(arr, mid + 1, r, x);
    }
    return -1;
}
  1. Bubble Sort implementation:
void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - i - 1; j++)
            if (arr[j] > arr[j + 1])
                std::swap(arr[j], arr[j + 1]);
}
  1. Depth-First Search (DFS) implementation:
void dfs(int v, vector<vector<int>>& adj, vector<bool>& visited) {
    visited[v] = true;
    for (int u : adj[v]) {
        if (!visited[u])
            dfs(u, adj, visited);
    }
}

Getting Started

To use the algorithms in this repository:

  1. Clone the repository:

    git clone https://github.com/TheAlgorithms/C-Plus-Plus.git
    
  2. Navigate to the desired algorithm's directory.

  3. Compile the C++ file:

    g++ -std=c++17 algorithm_name.cpp -o algorithm_name
    
  4. Run the compiled executable:

    ./algorithm_name
    

Note: Make sure you have a C++ compiler (e.g., g++) installed on your system.

Competitor Comparisons

183,979

All Algorithms implemented in Python

Pros of Python

  • Easier to read and write due to simpler syntax
  • Faster development time for algorithms
  • Extensive standard library and third-party packages

Cons of Python

  • Generally slower execution speed for complex algorithms
  • Less memory-efficient compared to C++
  • Lack of static typing can lead to runtime errors

Code Comparison

Python implementation of bubble sort:

def bubble_sort(arr):
    n = len(arr)
    for i in range(n):
        for j in range(0, n - i - 1):
            if arr[j] > arr[j + 1]:
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
    return arr

C++ implementation of bubble sort:

void bubbleSort(int arr[], int n) {
    for (int i = 0; i < n - 1; i++)
        for (int j = 0; j < n - i - 1; j++)
            if (arr[j] > arr[j + 1])
                swap(arr[j], arr[j + 1]);
}

The Python version is more concise and readable, while the C++ version offers better performance for large datasets. Both repositories provide a comprehensive collection of algorithms, but C-Plus-Plus focuses on efficiency and low-level implementation, while Python emphasizes simplicity and ease of understanding.

58,536

All Algorithms implemented in Java

Pros of Java

  • More extensive collection of algorithms and data structures
  • Better organized directory structure with clear categorization
  • More comprehensive documentation and comments within the code

Cons of Java

  • Slower execution speed compared to C++
  • Higher memory usage due to Java's runtime environment
  • Less low-level control over system resources

Code Comparison

Java implementation of Bubble Sort:

for (int i = 0; i < n - 1; i++)
    for (int j = 0; j < n - i - 1; j++)
        if (arr[j] > arr[j + 1]) {
            int temp = arr[j];
            arr[j] = arr[j + 1];
            arr[j + 1] = temp;
        }

C++ implementation of Bubble Sort:

for (int i = 0; i < n - 1; i++)
    for (int j = 0; j < n - i - 1; j++)
        if (arr[j] > arr[j + 1])
            swap(arr[j], arr[j + 1]);

The Java implementation is slightly more verbose due to the explicit swapping of elements, while C++ uses the built-in swap function. Both repositories offer a wide range of algorithms and data structures, making them valuable resources for learning and reference. The choice between them largely depends on the user's preferred programming language and specific requirements for performance and memory usage.

📝 Algorithms and data structures implemented in JavaScript with explanations and links to further readings

Pros of javascript-algorithms

  • Written in JavaScript, a widely-used language for web development
  • Includes explanations and links to further reading for each algorithm
  • Organized into categories (e.g., Math, String, Tree) for easy navigation

Cons of javascript-algorithms

  • Fewer algorithms implemented compared to C-Plus-Plus
  • Less focus on performance optimizations specific to low-level languages
  • May not be as suitable for system-level programming or embedded systems

Code Comparison

C-Plus-Plus implementation of binary search:

int binary_search(int arr[], int l, int r, int x) {
    if (r >= l) {
        int mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return binary_search(arr, l, mid - 1, x);
        return binary_search(arr, mid + 1, r, x);
    }
    return -1;
}

javascript-algorithms implementation of binary search:

function binarySearch(sortedArray, seekElement) {
  let startIndex = 0;
  let endIndex = sortedArray.length - 1;
  while (startIndex <= endIndex) {
    const middleIndex = startIndex + Math.floor((endIndex - startIndex) / 2);
    if (sortedArray[middleIndex] === seekElement) {
      return middleIndex;
    }
    if (sortedArray[middleIndex] < seekElement) {
      startIndex = middleIndex + 1;
    } else {
      endIndex = middleIndex - 1;
    }
  }
  return -1;
}

Minimal examples of data structures and algorithms in Python

Pros of algorithms

  • Written in Python, which is often considered more beginner-friendly and readable
  • Includes implementations of machine learning algorithms
  • Offers a wider variety of algorithm categories, including neural networks and backtracking

Cons of algorithms

  • Less comprehensive coverage of data structures compared to C-Plus-Plus
  • May be slower in execution for certain algorithms due to Python's interpreted nature
  • Lacks some advanced C++ features like templates and operator overloading

Code Comparison

algorithms (Python):

def binary_search(list, item):
    low = 0
    high = len(list) - 1
    while low <= high:
        mid = (low + high) // 2
        guess = list[mid]
        if guess == item:
            return mid

C-Plus-Plus (C++):

template <typename T>
int binary_search(const std::vector<T>& arr, const T& target) {
    int left = 0;
    int right = arr.size() - 1;
    while (left <= right) {
        int mid = left + (right - left) / 2;
        if (arr[mid] == target)
            return mid;

Both repositories offer valuable resources for learning and implementing algorithms. C-Plus-Plus provides a more comprehensive collection of data structures and algorithms in C++, while algorithms offers a broader range of algorithm categories in Python, including machine learning implementations. The choice between them depends on the preferred programming language and specific algorithmic needs of the user.

120+ interactive Python coding interview challenges (algorithms and data structures). Includes Anki flashcards.

Pros of interactive-coding-challenges

  • Focuses on interactive learning with Jupyter notebooks
  • Covers a wide range of topics including data structures, algorithms, and system design
  • Includes comprehensive test cases and solutions for each challenge

Cons of interactive-coding-challenges

  • Limited to Python implementations
  • May not cover as many specific algorithms as C-Plus-Plus
  • Less frequent updates compared to C-Plus-Plus

Code Comparison

C-Plus-Plus (Binary Search implementation):

int binary_search(int arr[], int l, int r, int x) {
    if (r >= l) {
        int mid = l + (r - l) / 2;
        if (arr[mid] == x)
            return mid;
        if (arr[mid] > x)
            return binary_search(arr, l, mid - 1, x);
        return binary_search(arr, mid + 1, r, x);
    }
    return -1;
}

interactive-coding-challenges (Binary Search implementation):

def binary_search(array, target):
    if array is None or target is None:
        return None
    left, right = 0, len(array) - 1
    while left <= right:
        mid = (left + right) // 2
        if array[mid] == target:
            return mid
        elif array[mid] < target:
            left = mid + 1
        else:
            right = mid - 1
    return None

:fireworks:Interactive Online Platform that Visualizes Algorithms from Code

Pros of algorithm-visualizer

  • Interactive visualization of algorithms, enhancing understanding
  • Supports multiple programming languages
  • User-friendly interface for learning and teaching algorithms

Cons of algorithm-visualizer

  • Limited to a specific set of algorithms
  • May not be as comprehensive as C-Plus-Plus for C++ implementations
  • Focuses on visualization rather than in-depth code explanations

Code Comparison

algorithm-visualizer (JavaScript):

const tracers = {
  array: Array2DTracer,
  chart: ChartTracer,
  graph: GraphTracer,
  // ...
};

C-Plus-Plus (C++):

template <class T>
T linear_search(const std::vector<T> &arr, const T &key) {
    for (size_t i = 0; i < arr.size(); i++) {
        if (arr[i] == key) return i;
    }
    return -1;
}

algorithm-visualizer provides a more visual and interactive approach to learning algorithms, while C-Plus-Plus offers a comprehensive collection of C++ implementations. The former is better for beginners and visual learners, while the latter is more suitable for those looking to study and implement algorithms in C++.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

The Algorithms - C++ # {#mainpage}

Gitpod Ready-to-Code CodeQL CI Gitter chat contributions welcome GitHub repo size Doxygen CI Awesome CI Income Discord chat Donate

Overview

This repository is a collection of open-source implementation of a variety of algorithms implemented in C++ and licensed under MIT License. These algorithms span a variety of topics from computer science, mathematics and statistics, data science, machine learning, engineering, etc.. The implementations and the associated documentation are meant to provide a learning resource for educators and students. Hence, one may find more than one implementation for the same objective but using a different algorithm strategies and optimizations.

Features

  • The repository provides implementations of various algorithms in one of the most fundamental general purpose languages - C++.
  • Well documented source code with detailed explanations provide a valuable resource for educators and students alike.
  • Each source code is atomic using STL classes and no external libraries are required for their compilation and execution. Thus, the fundamentals of the algorithms can be studied in much depth.
  • Source codes are compiled and tested for every commit on the latest versions of three major operating systems viz., Windows, MacOS, and Ubuntu (Linux) using MSVC 19 2022, AppleClang 14.0.0, and GNU 11.3.0 respectively.
  • Strict adherence to C++11 standard ensures portability of code to embedded systems as well like ESP32, ARM Cortex, etc. with little to no changes.
  • Self-checks within programs ensure correct implementations with confidence.
  • Modular implementations and OpenSource licensing enable the functions to be utilized conveniently in other applications.

Documentation

Online Documentation is generated from the repository source codes directly. The documentation contains all resources including source code snippets, details on execution of the programs, diagrammatic representation of program flow, and links to external resources where necessary. The documentation also introduces interactive source code with links to documentation for C++ STL library functions used. Click on Files menu to see the list of all the files documented with the code.

Documentation of Algorithms in C++ by The Algorithms Contributors is licensed under CC BY-SA 4.0
Creative Commons LicenseCredit must be given to the creatorAdaptations must be shared under the same terms

Contributions

As a community developed and maintained repository, we welcome new un-plagiarized quality contributions. Please read our Contribution Guidelines.