Skip to content

Commit 7cbfba3

Browse files
Merge branch 'master' into master
2 parents 728ddde + 4b740d4 commit 7cbfba3

File tree

9 files changed

+630
-74
lines changed

9 files changed

+630
-74
lines changed

.github/workflows/codeql.yml

Lines changed: 50 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1,51 +1,61 @@
1-
name: "CodeQL"
1+
name: "Code Scanning - Action"
22

33
on:
44
push:
5-
branches: [ "master" ]
5+
branches: [master]
66
pull_request:
7-
branches: [ "master" ]
7+
branches: [master]
8+
schedule:
9+
# ┌───────────── minute (0 - 59)
10+
# │ ┌───────────── hour (0 - 23)
11+
# │ │ ┌───────────── day of the month (1 - 31)
12+
# │ │ │ ┌───────────── month (1 - 12 or JAN-DEC)
13+
# │ │ │ │ ┌───────────── day of the week (0 - 6 or SUN-SAT)
14+
# │ │ │ │ │
15+
# │ │ │ │ │
16+
# │ │ │ │ │
17+
# * * * * *
18+
- cron: '30 1 * * 0'
819

920
jobs:
10-
analyze:
11-
name: Analyze
21+
CodeQL-Build:
22+
# CodeQL runs on ubuntu-latest, windows-latest, and macos-latest
1223
runs-on: ubuntu-latest
24+
1325
permissions:
26+
# required for all workflows
27+
security-events: write
28+
29+
# only required for workflows in private repositories
1430
actions: read
1531
contents: read
16-
security-events: write
32+
1733
steps:
18-
- name: Checkout repository
19-
uses: actions/checkout@v3
20-
- name: Initialize CodeQL
21-
uses: github/codeql-action/init@v2
22-
with:
23-
languages: cpp
24-
# If you wish to specify custom queries, you can do so here or in a config file.
25-
# By default, queries listed here will override any specified in a config file.
26-
# Prefix the list here with "+" to use these queries and those in the config file.
27-
28-
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
29-
# queries: security-extended,security-and-quality
30-
31-
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
32-
# If this step fails, then you should remove it and run the build manually (see below)
33-
- name: Autobuild
34-
uses: github/codeql-action/autobuild@v2
35-
36-
# ℹ️ Command-line programs to run using the OS shell.
37-
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
38-
39-
# If the Autobuild fails above, remove it and uncomment the following three lines.
40-
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
41-
42-
# - run: |
43-
# echo "Run, Build Application using script"
44-
# ./location_of_script_within_repo/buildscript.sh
45-
#
46-
# In our case, this would be a CMake build step.
47-
48-
- name: Perform CodeQL Analysis
49-
uses: github/codeql-action/analyze@v2
50-
with:
51-
category: "/language:cpp"
34+
- name: Checkout repository
35+
uses: actions/checkout@v3
36+
37+
# Initializes the CodeQL tools for scanning.
38+
- name: Initialize CodeQL
39+
uses: github/codeql-action/init@v2
40+
# Override language selection by uncommenting this and choosing your languages
41+
with:
42+
languages: cpp
43+
44+
# Autobuild attempts to build any compiled languages (C/C++, C#, Go, or Java).
45+
# If this step fails, then you should remove it and run the build manually (see below).
46+
- name: Autobuild
47+
uses: github/codeql-action/autobuild@v2
48+
49+
# ℹ️ Command-line programs to run using the OS shell.
50+
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
51+
52+
# ✏️ If the Autobuild fails above, remove it and uncomment the following
53+
# three lines and modify them (or add more) to build your code if your
54+
# project uses a compiled language
55+
56+
#- run: |
57+
# make bootstrap
58+
# make release
59+
60+
- name: Perform CodeQL Analysis
61+
uses: github/codeql-action/analyze@v2

CONTRIBUTING.md

Lines changed: 84 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ You can add new algorithms or data structures that are **not present in the repo
3333
- Make sure the file extensions are `*.hpp`, `*.h` or `*.cpp`.
3434
- Don't use **`bits/stdc++.h`** because this is quite Linux-specific and slows down the compilation process.
3535
- Organize your code using **`struct`**, **`class`**, and/or **`namespace`** keywords.
36-
- If an implementation of the algorithm already exists, please refer to the [file-name section below](#new-file-name-guidelines).
36+
- If an implementation of the algorithm already exists, please refer to the [file-name section below](#file-name-guidelines).
3737
- You can suggest reasonable changes to existing algorithms.
3838
- Strictly use snake_case (underscore_separated) in filenames.
3939
- If you have added or modified code, please make sure the code compiles before submitting.
@@ -54,13 +54,91 @@ You can add new algorithms or data structures that are **not present in the repo
5454
- Make sure to add examples and test cases in your `main()` function.
5555
- If you find an algorithm or document without tests, please feel free to create a pull request or issue describing suggested changes.
5656
- Please try to add one or more `test()` functions that will invoke the algorithm implementation on random test data with the expected output. Use the `assert()` function to confirm that the tests will pass. Requires including the `cassert` library.
57+
- Test cases should fully verify that your program works as expected. Rather than asking the user for input, it's best to make sure the given output is the correct output.
58+
59+
##### Self-test examples
60+
61+
1. [Quick sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/sorting/quick_sort.cpp#L137) testing (complex).
62+
63+
```cpp
64+
// Let's make sure the array of numbers is ordered after calling the function.
65+
std::vector<uint64_t> arr = {5, 3, 8, 12, 14, 16, 28, 96, 2, 5977};
66+
std::vector<uint64_t> arr_sorted = sorting::quick_sort::quick_sort(
67+
arr, 0, int(std::end(arr) - std::begin(arr)) - 1);
68+
69+
assert(std::is_sorted(std::begin(arr_sorted), std::end(arr_sorted)));
70+
```
71+
72+
2. [Subset Sum](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/backtracking/subset_sum.cpp#L58) testing (medium).
73+
74+
```cpp
75+
std::vector<int32_t> array1 = {-7, -3, -2, 5, 8}; // input array
76+
assert(backtracking::subset_sum::number_of_subsets(0, array1) ==
77+
2); // first argument in subset_sum function is the required sum and
78+
// second is the input array
79+
```
80+
81+
3. Small C++ program that showcases and explains the use of tests.
82+
83+
```cpp
84+
#include <iostream> /// for IO operations
85+
#include <vector> /// for std::vector
86+
#include <cassert> /// for assert
87+
88+
/**
89+
* @brief Verifies if the given array
90+
* contains the given number on it.
91+
* @tparam T the type of array (e.g., `int`, `float`, etc.)
92+
* @param arr the array to be used for checking
93+
* @param number the number to check if it's inside the array
94+
* @return false if the number was NOT found in the array
95+
* @return true if the number WAS found in the array
96+
*/
97+
template <typename T>
98+
bool is_number_on_array(const std::vector<T> &arr, const int &number) {
99+
for (int i = 0; i < sizeof(arr) / sizeof(int); i++) {
100+
if (arr[i] == number) {
101+
return true;
102+
}
103+
else {
104+
// Number not in the current index, keep searching.
105+
}
106+
}
107+
108+
return false;
109+
}
110+
111+
/**
112+
* @brief Self-test implementations
113+
* @returns void
114+
*/
115+
static void tests() {
116+
std::vector<int> arr = { 9, 14, 21, 98, 67 };
117+
118+
assert(is_number_on_array(arr, 9) == true);
119+
assert(is_number_on_array(arr, 4) == false);
120+
assert(is_number_on_array(arr, 98) == true);
121+
assert(is_number_on_array(arr, 512) == false);
122+
123+
std::cout << "All tests have successfully passed!\n";
124+
}
125+
126+
/**
127+
* @brief Main function
128+
* @returns 0 on exit
129+
*/
130+
int main() {
131+
tests(); // run self-test implementations
132+
return 0;
133+
}
134+
```
57135
58136
#### Typical structure of a program
59137
60138
```cpp
61139
/**
62140
* @file
63-
* @brief Add one line description here. Should contain a Wikipedia
141+
* @brief Add one-line description here. Should contain a Wikipedia
64142
* link or another source explaining the algorithm/implementation.
65143
* @details
66144
* This is a multi-line
@@ -74,7 +152,7 @@ You can add new algorithms or data structures that are **not present in the repo
74152
#include /// for `some function here`
75153
76154
/**
77-
* @namespace <folder name>
155+
* @namespace
78156
* @brief <namespace description>
79157
*/
80158
namespace name {
@@ -119,6 +197,9 @@ static void test() {
119197
assert(func(...) == ...); // this ensures that the algorithm works as expected
120198
121199
// can have multiple checks
200+
201+
// this lets the user know that the tests have passed
202+
std::cout << "All tests have successfully passed!\n";
122203
}
123204
124205
/**

DIRECTORY.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -375,6 +375,7 @@
375375
* [Shell Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/sorting/shell_sort.cpp)
376376
* [Shell Sort2](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/sorting/shell_sort2.cpp)
377377
* [Slow Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/sorting/slow_sort.cpp)
378+
* [Stooge Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/sorting/stooge_sort.cpp)
378379
* [Strand Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/sorting/strand_sort.cpp)
379380
* [Swap Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/sorting/swap_sort.cpp)
380381
* [Tim Sort](https://github.com/TheAlgorithms/C-Plus-Plus/blob/HEAD/sorting/tim_sort.cpp)

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
<!-- the suffix in the above line is required for doxygen to consider this as the index page of the generated documentation site -->
33

44
[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/TheAlgorithms/C-Plus-Plus)
5-
[![CodeQL CI](https://github.com/TheAlgorithms/C-Plus-Plus/actions/workflows/codeql.yml/badge.svg)](https://github.com/TheAlgorithms/C-Plus-Plus/actions/workflows/codeql_analysis.yml)
5+
[![CodeQL CI](https://github.com/TheAlgorithms/C-Plus-Plus/actions/workflows/codeql.yml/badge.svg)](https://github.com/TheAlgorithms/C-Plus-Plus/actions/workflows/codeql.yml)
66
[![Gitter chat](https://img.shields.io/badge/Chat-Gitter-ff69b4.svg?label=Chat&logo=gitter&style=flat-square)](https://gitter.im/TheAlgorithms)
77
[![contributions welcome](https://img.shields.io/static/v1.svg?label=Contributions&message=Welcome&color=0059b3&style=flat-square)](https://github.com/TheAlgorithms/C-Plus-Plus/blob/master/CONTRIBUTING.md)
88
![GitHub repo size](https://img.shields.io/github/repo-size/TheAlgorithms/C-Plus-Plus?color=red&style=flat-square)

data_structures/segment_tree.cpp

Lines changed: 133 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,133 @@
1+
/**
2+
* @file
3+
* @brief A data structure to quickly do operations on ranges: the [Segment Tree](https://en.wikipedia.org/wiki/Segment_tree) algorithm implementation
4+
* @details
5+
* Implementation of the segment tree data structre
6+
*
7+
* Can do point updates (updates the value of some position)
8+
* and range queries, where it gives the value of some associative
9+
* opperation done on a range
10+
*
11+
* Both of these operations take O(log N) time
12+
* @author [Nishant Chatterjee](https://github.com/nishantc1527)
13+
*/
14+
15+
#include <iostream> /// For IO operations
16+
#include <vector> /// For std::vector
17+
#include <algorithm> /// For std::min and std::max
18+
#include <cassert> /// For assert
19+
20+
/*
21+
* @namespace
22+
* @brief Data structures
23+
*/
24+
namespace data_structures {
25+
/**
26+
* @brief class representation of the segment tree
27+
* @tparam T The type of the class that goes in the datastructure
28+
*/
29+
template <class T>
30+
class SegmentTree {
31+
private:
32+
const T ID = 0; ///< Comb(ID, x) = x
33+
std::vector<T> t; ///< Vector to represent the tree
34+
int size = 0; ///< Number of elements available for querying in the tree
35+
private:
36+
/**
37+
* @brief Any associative function that combines x and y
38+
* @param x The first operand
39+
* @param y The second operand
40+
* @return Some associative operation applied to these two values. In this case, I used addition
41+
*/
42+
T comb(T x, T y) {
43+
return x + y;
44+
}
45+
/**
46+
* @brief Gives the midpoint between two integers
47+
* @param l The left endpoint
48+
* @param r The right endpoint
49+
* @return the middle point between them
50+
*/
51+
int mid(int l, int r) {
52+
return l + (r - l) / 2;
53+
}
54+
/**
55+
* @brief Helper method for update method below
56+
* @param i The index of the current node
57+
* @param l The leftmost node of the current node
58+
* @param r The rightmost node of the current node
59+
* @param pos The position to update
60+
* @param val The value to update it to
61+
*/
62+
void update(int i, int l, int r, int pos, T val) {
63+
if(l == r) t[i] = val;
64+
else {
65+
int m = mid(l, r);
66+
if(pos <= m) update(i * 2, l, m, pos, val);
67+
else update(i * 2 + 1, m + 1, r, pos, val);
68+
t[i] = comb(t[i * 2], t[i * 2 + 1]);
69+
}
70+
}
71+
/**
72+
* @brief Helper method for range_comb method below
73+
* @param i The current node
74+
* @param l The leftmost node of the current node
75+
* @param r The rightmost node of the current node
76+
* @param tl The left endpoint of the range
77+
* @param tr The right endpoint of the range
78+
* @return The comb operation applied to all values between tl and tr
79+
*/
80+
T range_comb(int i, int l, int r, int tl, int tr) {
81+
if(l == tl && r == tr) return t[i];
82+
if(tl > tr) return 0;
83+
int m = mid(l, r);
84+
return comb(range_comb(i * 2, l, m, tl, std::min(tr, m)), range_comb(i * 2 + 1, m + 1, r, std::max(tl, m + 1), tr));
85+
}
86+
public:
87+
SegmentTree(int n) : t(n * 4, ID), size(n) {}
88+
/**
89+
* @brief Updates a value at a certain position
90+
* @param pos The position to update
91+
* @param val The value to update it to
92+
*/
93+
void update(int pos, T val) {
94+
update(1, 1, size, pos, val);
95+
}
96+
/**
97+
* @brief Returns comb across all values between l and r
98+
* @param l The left endpoint of the range
99+
* @param r The right endpoint of the range
100+
* @return The value of the comb operations
101+
*/
102+
T range_comb(int l, int r) {
103+
return range_comb(1, 1, size, l, r);
104+
}
105+
};
106+
} // namespace data_structures
107+
108+
/**
109+
* @brief Self-test implementations
110+
* @returns void
111+
*/
112+
static void test() {
113+
data_structures::SegmentTree<int> t(5);
114+
t.update(1, 1);
115+
t.update(2, 2);
116+
t.update(3, 3);
117+
t.update(4, 4);
118+
t.update(5, 5);
119+
assert(t.range_comb(1, 3) == 6); // 1 + 2 + 3 = 6
120+
t.update(1, 3);
121+
assert(t.range_comb(1, 3) == 8); // 3 + 2 + 3 = 8
122+
123+
std::cout << "All tests have successfully passed!\n";
124+
}
125+
126+
/**
127+
* @brief Main function
128+
* @returns 0 on exit
129+
*/
130+
int main() {
131+
test(); // run self-test implementations
132+
return 0;
133+
}

0 commit comments

Comments
 (0)