From 8fcdba9741a0bfdf243691234a8662fbaa82fa22 Mon Sep 17 00:00:00 2001 From: nash4826 <84267693+nash4826@users.noreply.github.com> Date: Wed, 26 Jan 2022 22:06:18 +0900 Subject: [PATCH 01/91] chore(C): add tower of Hanoi using recursion (#681) --- algorithms/C/README.md | 6 +- algorithms/C/recursion/tower-of-hanoi.c | 101 ++++++++++++++++++++++++ 2 files changed, 106 insertions(+), 1 deletion(-) create mode 100644 algorithms/C/recursion/tower-of-hanoi.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index adb67ee7..ecae21ba 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -39,6 +39,10 @@ - [Double Ended Queue using array](queues/double-ended-queue-using-array.c) - [Circular Queue using array](queues/circular-queue-using-array.c) +## Recursion + +- [Tower of Hanoi](recursion/tower-of-hanoi.c) + ## Sorting - [Bubble Sort](sorting/bubble-sort.c) @@ -74,4 +78,4 @@ ## Stacks - [Stack using arrays](stacks/stack-using-arrays.c) -- [Stack using Linked List](stacks/stack-using-linked-list.c) \ No newline at end of file +- [Stack using Linked List](stacks/stack-using-linked-list.c) diff --git a/algorithms/C/recursion/tower-of-hanoi.c b/algorithms/C/recursion/tower-of-hanoi.c new file mode 100644 index 00000000..5e4e806b --- /dev/null +++ b/algorithms/C/recursion/tower-of-hanoi.c @@ -0,0 +1,101 @@ +#include +/* + *Tower of Hanoi* + + *Rule: + + 1. Only one disk can be moved at a time. + 2. Each move consists of taking the upper disk from one of the stacks + and placing it on top of another stack i.e. + a disk can only be moved if it is the uppermost disk on a stack. + 3. No disk may be placed on top of a smaller disk. + + * Time Complexity : O(2^n) + * Space Complexity: O(n) +*/ + + +void towerOfHanoi(int disk, char from, char by, char to) +{ + if (disk == 1) // If the number of disks to move is one + { + printf("Move disk 1 from %c to %c \n", from, to); + } + else + { + towerOfHanoi(disk - 1, from, to, by); + printf("Move disk %d from %c to %c \n", disk, from, to); + towerOfHanoi(disk - 1, by, from, to); + } + +} + +int main() +{ + int disk; + + printf("Enter the number of disks you want : "); + scanf("%d", &disk); + + // Move N disks of Tower A to Tower C via Tower B + towerOfHanoi(disk, 'A', 'B', 'C'); + + return 0; +} + +/* + Sample + + input | output + | + disk : 3 | Move disk 1 from A to C + | Move disk 2 from A to B + | Move disk 1 from C to B + | Move disk 3 from A to C + | Move disk 1 from B to A + | Move disk 2 from B to C + | Move disk 1 from A to C + + +--------------------------------------------------------------------------- + + + **Image illustration for 3 disks** + + + standby step 1 + + A B C A B C + + | | | | | | + | | | | | | + ###(1) | | | | | + #####(2) | | ##### | | +_#######(3)|______|__ _#######______|_______###_ + + + + step 2 step 3 step 4 + + A B C A B C A B C + + | | | | | | | | | + | | | | | | | | | + | | | | | | | | | + | | | | ### | | ### | +_#######_#####___###__ #######__#####____|___ __|_____#####__#######__ + + + + step 5 step 6 step 7 + + A B C A B C A B C + + | | | | | | | | | + | | | | | | | | | + | | | | | | | | ### + | | | | | ##### | | ##### +___###___#####_#######_ ___###_____|___#######_ __|________|_____#######__ + + +*/ From 5bfa1de2fcd9aba9f943618cc55cca4429e545ea Mon Sep 17 00:00:00 2001 From: Anish <87910771+AnishLohiya@users.noreply.github.com> Date: Wed, 2 Feb 2022 11:03:55 +0530 Subject: [PATCH 02/91] chore(C): add shell sort (#678) --- algorithms/C/README.md | 1 + algorithms/C/sorting/shell-sort.c | 51 +++++++++++++++++++++++++++++++ 2 files changed, 52 insertions(+) create mode 100644 algorithms/C/sorting/shell-sort.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index ecae21ba..77a27dbe 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -51,6 +51,7 @@ - [Heap Sort](sorting/heap-sort.c) - [Selection Sort](sorting/selection-sort.c) - [Quick Sort](sorting/quick-sort.c) +- [Shell Sort](sorting/shell-sort.c) ## Strings diff --git a/algorithms/C/sorting/shell-sort.c b/algorithms/C/sorting/shell-sort.c new file mode 100644 index 00000000..15de8179 --- /dev/null +++ b/algorithms/C/sorting/shell-sort.c @@ -0,0 +1,51 @@ +#include + +// Shell Sort +void ShellSort(int a[], int n) +{ + int i, j, k, temp; + // Rearrange elements at each n/2, n/4, n/8, ... intervals + for (i = n / 2; i > 0; i /= 2) + { + for (j = i; j < n; j++) + { + temp = a[j]; + for (k = j; k >= i && a[k - i] > temp; k -= i) + { + a[k] = a[k - i]; + } + a[k] = temp; + } + } +} + +// Prints the array +void printArray(int a[], int size) +{ + for (int i = 0; i < size; ++i) + { + printf("%d ", a[i]); + } +} + +int main() +{ + int a[] = {64, 25, 12, 22, 11, 90}; + int n = sizeof(a) / sizeof(a[0]); + printf("Array before sorting:\n"); + printArray(a, n); + ShellSort(a, n); + printf("\nArray after sorting:\n"); + printArray(a, n); + return 0; +} + +/* +Output: +Array before sorting: +64 25 12 22 11 90 +Array after sorting: +11 12 22 25 64 90 + +Time Complexity: O(n log n) +*/ From 1a1ddbe152640d829e63f1388a5bafc7b127e6e9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Alim=20Kerem=20Erdo=C4=9Fmu=C5=9F?= Date: Mon, 7 Feb 2022 17:57:42 +0300 Subject: [PATCH 03/91] docs: add Turkish language (#698) --- docs/tr/CONTRIBUTING.md | 28 ++++++++++++++++++++++++++ docs/tr/README.md | 9 +++++++++ docs/tr/Strings/Palindrom.md | 38 ++++++++++++++++++++++++++++++++++++ 3 files changed, 75 insertions(+) create mode 100644 docs/tr/CONTRIBUTING.md create mode 100644 docs/tr/README.md create mode 100644 docs/tr/Strings/Palindrom.md diff --git a/docs/tr/CONTRIBUTING.md b/docs/tr/CONTRIBUTING.md new file mode 100644 index 00000000..c7668148 --- /dev/null +++ b/docs/tr/CONTRIBUTING.md @@ -0,0 +1,28 @@ +# Algoritma Adı + +Algoritmanın kısa bir açıklamasını aşağıdaki gibi yazın: +1. Zaman Karmaşıklığı +2. Uzay Karmaşıklığı +3. Uygulamalar +4. Kurucunun Adı +5. vb... + +## Adımlar +Algoritmayı açık, basit ve anlaşılır adımlarla tanımlayın. + +## Örnek +Algoritmayı örnek giriş verileriyle izleyin. + +## Uygulama + +Programlama dillerindeki uygulamalarına bağlantıları ekleyin. +NOT: Bağlantılar yalnızca algoritmalar klasöründe olmalıdır. + +## Video Linkleri + +Algoritmayı açıklayan bir videonun URL'sini ekleyin. + +## Diğer + +Diğer bilgileri bu kısımda verebilirsiniz. + diff --git a/docs/tr/README.md b/docs/tr/README.md new file mode 100644 index 00000000..909cfd16 --- /dev/null +++ b/docs/tr/README.md @@ -0,0 +1,9 @@ +# Algoritmalar + +## Dizme Algoritmaları + +- [Palindrom](./Strings/Palindrom.md) + +## Diğer + +[Yeni algoritma dökümantasyonunu nasıl eklerim?](./CONTRIBUTING.md) diff --git a/docs/tr/Strings/Palindrom.md b/docs/tr/Strings/Palindrom.md new file mode 100644 index 00000000..88c1e405 --- /dev/null +++ b/docs/tr/Strings/Palindrom.md @@ -0,0 +1,38 @@ +# Palindrom +Palindrom, ileriye ve geriye doğru okunduğunda aynı bir kelime, deyim, sayı veya kelimeyi oluşturan özel bir kelime dizisidir. Palindrom oluşturulurken sözcükler veya harfler arasında noktalama ve boşluklar olabilir. + +## Adımlar +1. Tüm noktalama işaretlerini ve boşlukları kaldırarak ve tüm harfleri küçük harfe dönüştürerek kelimeyi düzenleyin. +2. Düzenleme sırasını tersine çevirin. +3. Düzenlenmiş kelime dizisi, ters çevrilmiş diziyle aynıysa, o zaman bir palindrom oluşturmuş olursunuz. + +## Örnekler + +### Tek Kelimeden Oluşan Palindromlar +- Ulu +- Ütü +- Velev +- Verev +- Yapay + +### Çok Kelimeden Oluşan Palindromlar +- Ah adi demir erimedi daha. +- Al kazık çak karaya kayarak kaç kızakla. +- Al yarısını sırayla. + +## Uygulamalar +- [C](../../../algorithms/C/strings/palindrome.c) +- [C++](../../../algorithms/CPlusPlus/Maths/palindrome.cpp) +- [C#](../../../algorithms/CSharp/src/Strings/palindrome.cs) +- [Haskell](../../../algorithms/Haskell/strings/palindrome.hs) +- [Java](../../../algorithms/Java/strings/palindrome.java) +- [JavaScript](../../../algorithms/JavaScript/src/strings/palindrome.js) +- [Python](../../../algorithms/Python/strings/palindrome.py) +- [Rust](../../../algorithms/Rust/strings/palindrome/src/main.rs) + +## Video Linki +[Palindrom Algoritmasını Açıklayan Coursera videosu](https://www.coursera.org/lecture/program-code/palindrome-algorithm-1-zzQqs) + +## Diğer Linkler +[Wikipedia](https://tr.wikipedia.org/wiki/Palindrom) + From 350072da9e55b585f2f59233fa48b7faeb69c41c Mon Sep 17 00:00:00 2001 From: morkovka3 <74007089+morkovka3@users.noreply.github.com> Date: Mon, 7 Feb 2022 14:58:16 +0000 Subject: [PATCH 04/91] chore(Python): add Levenshtein distance (#685) --- algorithms/Python/README.md | 1 + .../levenshtein_distance.py | 41 +++++++++++++++++++ 2 files changed, 42 insertions(+) create mode 100644 algorithms/Python/dynamic_programming/levenshtein_distance.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 1b6b1eac..282dee29 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -60,6 +60,7 @@ - [N-th Term Of Fibonacci Series](dynamic_programming/fibonacci_series_nth_term.py) - [Catalan Sequence](dynamic_programming/catalan_sequence.py) - [0/1 Knapsack Problem](dynamic_programming/knapsack.py) +- [Levenshtein distance](dynamic_programming/levenshtein_distance.py) ## Graphs - [Simple Graph](graphs/graph.py) diff --git a/algorithms/Python/dynamic_programming/levenshtein_distance.py b/algorithms/Python/dynamic_programming/levenshtein_distance.py new file mode 100644 index 00000000..58e568a8 --- /dev/null +++ b/algorithms/Python/dynamic_programming/levenshtein_distance.py @@ -0,0 +1,41 @@ +# The Levenshtein distance (Edit distance) Problem + +# Informally, the Levenshtein distance between two words is +# the minimum number of single-character edits (insertions, deletions or substitutions) +# required to change one word into the other. + +# For example, the Levenshtein distance between kitten and sitting is 3. +# The minimal edit script that transforms the former into the latter is: + +# kitten —> sitten (substitution of s for k) +# sitten —> sittin (substitution of i for e) +# sittin —> sitting (insertion of g at the end) + +def levenshtein_distance(word_1, chars_1, word_2, chars_2): + # base case if the strings are empty + if chars_1 == 0: + return chars_2 + if chars_2 == 0: + return chars_1 + + # if last characters of the string match, the cost of + # operations is 0, i.e. no changes are made + if word_1[chars_1 - 1] == word_2[chars_2 - 1]: + cost = 0 + else: + cost = 1 + + # calculating the numbers of operations recursively + deletion = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2) + 1 + insertion = levenshtein_distance(word_1, chars_1, word_2, chars_2 - 1) + 1 + substitution = levenshtein_distance(word_1, chars_1 - 1, word_2, chars_2 - 1) + cost + + return min(deletion, insertion, substitution) + +# driving script +if __name__ == '__main__': + word_1 = 'plain' + word_2 = 'plane' + + print('The Levenshtein distance is:') + print(levenshtein_distance(word_1, len(word_1), word_2, len(word_2))) From 23595e9524b21035ae6de8ac72736a882cdb33c4 Mon Sep 17 00:00:00 2001 From: Radhika Bansal <96312216+Radhika403@users.noreply.github.com> Date: Mon, 7 Feb 2022 20:28:35 +0530 Subject: [PATCH 05/91] chore(Java): add target-sum-subsets problem (#687) --- .../Java/backtracking/target-sum-subsets.java | 49 +++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 algorithms/Java/backtracking/target-sum-subsets.java diff --git a/algorithms/Java/backtracking/target-sum-subsets.java b/algorithms/Java/backtracking/target-sum-subsets.java new file mode 100644 index 00000000..6a386554 --- /dev/null +++ b/algorithms/Java/backtracking/target-sum-subsets.java @@ -0,0 +1,49 @@ +// Target sum subsets is a program to print all subsets of an array (given by user) such that sum of all elements in subset equal to a target sum given by user + +// Algorithm Type: Backtracking +// Time Complexity: O(2^N) + +import java.io.*; +import java.util.*; + +public class targetSumSubsets { + + public static void main(String[] args) throws Exception { + Scanner scn = new Scanner(System.in); + + // input size of array + int n = scn.nextInt(); + + // input elements of array + int[] arr = new int[n]; + for(int i=0; i Date: Mon, 7 Feb 2022 15:00:16 +0000 Subject: [PATCH 06/91] =?UTF-8?q?docs:=20add=20Portugu=C3=AAs=20language?= =?UTF-8?q?=20(#697)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + docs/pt/CONTRIBUTING.md | 29 ++++++++++++++++ docs/pt/Procura/Pesquisa-Binaria.md | 54 +++++++++++++++++++++++++++++ docs/pt/README.md | 13 +++++++ docs/pt/Strings/Palindrome.md | 43 +++++++++++++++++++++++ 5 files changed, 140 insertions(+) create mode 100644 docs/pt/CONTRIBUTING.md create mode 100644 docs/pt/Procura/Pesquisa-Binaria.md create mode 100644 docs/pt/README.md create mode 100644 docs/pt/Strings/Palindrome.md diff --git a/README.md b/README.md index 8d59a45b..cce11a1e 100644 --- a/README.md +++ b/README.md @@ -13,6 +13,7 @@ Data structure and Algorithm (DSA) ## Explanations - [English](./docs/en) +- [Português](.docs/pt) - [繁體中文](./docs/zh-tw) - [日本語](./docs/ja) diff --git a/docs/pt/CONTRIBUTING.md b/docs/pt/CONTRIBUTING.md new file mode 100644 index 00000000..68c9de2a --- /dev/null +++ b/docs/pt/CONTRIBUTING.md @@ -0,0 +1,29 @@ +# Nome do Algoritmo + +Escrever uma breve descrição de características do algoritmo assim como: +1. Complexidade de tempo +2. Complexidade de espaço +3. Aplicações +4. Nome dos fundadores/criadores +5. etc... + +## Passos + +Descreve o algoritmo de forma clara, simples e de modo que os passos sejam compreendidos por toda a gente. + +## Exemplos + +Ao dar exemplos, identifica o algoritmo com uma amostra de dados iniciais. E continua com eles ao fazer os passos. + +## Implementação + +A ligação(links) para a sua implementação na respetiva linguagem de programação. +NOTA: A ligação(link) deve estar apenas dentro da pasta do algoritmo. + +## Video URL + +Anexa o URL de um vídeo que explica o algoritmo, deve ser em português. + +## Outros + +Qualquer informação é sempre bem-vinda e deve ser incluída nesta secção. \ No newline at end of file diff --git a/docs/pt/Procura/Pesquisa-Binaria.md b/docs/pt/Procura/Pesquisa-Binaria.md new file mode 100644 index 00000000..c9f2f856 --- /dev/null +++ b/docs/pt/Procura/Pesquisa-Binaria.md @@ -0,0 +1,54 @@ +# Pesquisa Binária + +A **Pesquisa Binária**(em inglês Binary Search) é um algoritmo de pesquisa que encontra a posição de um valor dentro da matriz. + +1. Complexidade temporal: O(log n) +2. Complexidade de espaço: O(1) +3. Aplicações: Uma melhor aplicação quando os dados já estão organizados e temos bastantes +4. Nome do fundador: P.F. Windley, A.D. Booth, A.J.T. Colin, e T.N. Hibbard +5. É um dos algoritmos de pesquisa mais populares e usado diariamente. + +## Passos + +1. Encontrar o elemento do meio da matriz +2. Verificar se o elemento que estamos a procurar é igual ao elemento do meio e se sim, retornar o índice e acabar o programa/função. +3. Se o 2º passo não foi verificado, testamos se o elemento a procurar é menor que o elemento do meio, se sim voltamos para o passo 1 e usamos entre o início do matriz e o índice do elemento do meio -1. +4. Se o 3º passo não foi verificado, testamos se o elemento a procurar é maior que o elemento do meio, se sim voltamos para o passo 1 e usamos entre o índice do elemento do meio +1 até ao último índice da matriz. +5. Percorrer o ciclo até o índice inicial ser menor do que o índice final +6. Se o ciclo acabar e nenhum dado for encontrado retornar -1, que significa que o elemento a procurar não existe na matriz dada. +> **Nota:** A matriz deve estar organizada de forma crescente. + +## Exemplos + +Dados de Entrada: **10,20,30,40,50** + +Elemento para procurar: **20** + +Procedimento: + +Elemento do meio: **30** e o elemento a procurar é menor do que 30, logo a pesquisa vai passar a ser do início do matriz até ao índice do meio -1 + +Logo em seguida o elemento do meio é o **20** e o elemento do meio é o elemento que estamos a procurar, logo retornar o índice **1** + +Dados de Saída: **1** + +## Implementações + +- [C](https://github.com/MakeContributions/DSA/blob/main/algorithms/C/searching/Binary-search.c) +- [C++](https://github.com/MakeContributions/DSA/blob/main/algorithms/CPlusPlus/Searching/binary-search.cpp) +- [CSharp](https://github.com/MakeContributions/DSA/blob/main/algorithms/CSharp/src/Search/binary-search.cs) +- [Go](https://github.com/MakeContributions/DSA/blob/main/algorithms/Go/searching/binary-search.go) +- [Java](https://github.com/MakeContributions/DSA/blob/main/algorithms/Java/searching/binary-search.java) +- [JavaScript](https://github.com/MakeContributions/DSA/blob/main/algorithms/JavaScript/src/searching/binary-search.js) +- [JavaScript](https://github.com/MakeContributions/DSA/blob/main/algorithms/JavaScript/src/searching/binary-search-recursive.js) +- [Python](https://github.com/MakeContributions/DSA/blob/main/algorithms/Python/searching/binary_search.py) + +## Video URL + +[Video a explicar pesquisa binária](https://www.youtube.com/watch?v=5T1SDEZzCLo) + +## Outros + +[Wikipédia](https://pt.wikipedia.org/wiki/Pesquisa_bin%C3%A1ria) + +[Exercícios e uma explicação mais detalhada](https://www2.unifap.br/furtado/files/2013/10/Algoritmos-busca-bin%c3%a1ria-vers%c3%a3o-simplificada1.pdf) \ No newline at end of file diff --git a/docs/pt/README.md b/docs/pt/README.md new file mode 100644 index 00000000..c6de0649 --- /dev/null +++ b/docs/pt/README.md @@ -0,0 +1,13 @@ +# Algoritmos + +## Strings + +- [Palíndromo](./Strings/Palindrome.md) + +## Procura + +- [Pesquisa Binária](./Procura/Pesquisa-Binaria.md) + +## Others + +[Como adicionar documentação para um algoritmo?](./CONTRIBUTING.md) diff --git a/docs/pt/Strings/Palindrome.md b/docs/pt/Strings/Palindrome.md new file mode 100644 index 00000000..9a33f7f9 --- /dev/null +++ b/docs/pt/Strings/Palindrome.md @@ -0,0 +1,43 @@ +## Palíndromo + +Um palíndromo é uma palavra, frase, número ou sequência de palavras que são lidas igualmente na forma normal e de trás para frente. + +## Passos + +1. Limpa a string removendo toda a pontuação e espaços em branco e converte todas as letras para minúsculas. +2. Inverte a string limpa (passo anterior). +3. Se a string limpa for igual à string limpa invertida temos um palíndromo. + +## Exemplos + +### Palíndromo de uma palavra +- Coco +- Ovo +- Osso +- Reler +- Salas + +## Frases palíndromas +- Socorram-me, subi no ônibus em Marrocos. +- A base do teto desaba. +- A mãe te ama. +- Arara rara. +- O céu sueco. + +## Implementações +- [C](../../../algorithms/C/strings/palindrome.c) +- [C++](../../../algorithms/CPlusPlus/Maths/palindrome.cpp) +- [C#](../../../algorithms/CSharp/src/Strings/palindrome.cs) +- [Haskell](../../../algorithms/Haskell/strings/palindrome.hs) +- [Java](../../../algorithms/Java/strings/palindrome.java) +- [JavaScript](../../../algorithms/JavaScript/src/strings/palindrome.js) +- [Python](../../../algorithms/Python/strings/palindrome.py) +- [Rust](../../../algorithms/Rust/strings/palindrome/src/main.rs) + +## Video URL +[Video no youtube a explicar o palíndromo](https://www.youtube.com/watch?v=j3yTHI8uSCg) + +## Outros + +[Wikipédia](https://pt.wikipedia.org/wiki/Pal%C3%ADndromo) +[Mais exemplos de palíndromos](https://www.todamateria.com.br/palindromo/) \ No newline at end of file From f55d4596457eb4a86cd5f45fbac81e6d401f1902 Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Mon, 7 Feb 2022 11:03:26 -0400 Subject: [PATCH 07/91] chore: skip Portuguese folder on code spell --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index f27a8ae2..587eef9e 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin" --quiet-level=2 --skip="**/**/package-lock.json" + - run: codespell --ignore-words-list="ans,nnumber,nin" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt" From 3b22e9c5e435c6c20fb0946370c8af6740a8b255 Mon Sep 17 00:00:00 2001 From: stutimohta20 <84969358+stutimohta20@users.noreply.github.com> Date: Mon, 7 Feb 2022 20:36:12 +0530 Subject: [PATCH 08/91] chore(CPlusPlus): add prefix to postfix stacks (#674) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Co-authored-by: Rahul Rajeev Pillai <66192267+Ashborn-SM@users.noreply.github.com> --- algorithms/CPlusPlus/README.md | 1 + .../CPlusPlus/Stacks/prefix_to_postfix.cpp | 64 +++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 algorithms/CPlusPlus/Stacks/prefix_to_postfix.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 86bef265..e62faa25 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -88,6 +88,7 @@ - [Stack using Array](Stacks/stack-using-array.cpp) - [Infix to postfix expression conversion](Stacks/infix-to-postfix.cpp) - [Stock Span Problem using Stacks](Stacks/stock-span-problem.cpp) +- [Prefix to Postfix expression conversion](Stacks/prefix_to_postfix.cpp) ## Sorting diff --git a/algorithms/CPlusPlus/Stacks/prefix_to_postfix.cpp b/algorithms/CPlusPlus/Stacks/prefix_to_postfix.cpp new file mode 100644 index 00000000..6c59421f --- /dev/null +++ b/algorithms/CPlusPlus/Stacks/prefix_to_postfix.cpp @@ -0,0 +1,64 @@ +// Program to convert a prefix expression to postfix expression +// Prefix expression : An expression in which the operator appears before the operands. +// Postfix expression : An expression in which the operator appears after the operands. + + + +// Alogorithm +// To convert prefix to postfix expression we follow steps given below: +// Step 1. If the symbol is an operand, push it to the stack +// Step 2. If symbol is an operator then pop top two elements from stack +// Step 3. Then push an expression by concatenating (+op1+op2+symbol) +// Step 4. At last return the top element of stack as postfix expression + + + +// CODE: +#include +using namespace std; + +// Function to convert prefix to postfix expression +string prefix_to_postfix(string prefix) +{ + stack s; + // length of prefix expression + int l=prefix.length(); + + // Iterating through the Prefix expression from right to left + for(int i=l-1;i>=0;i--){ + // if the symbol is an operand, push it to the stack + if(prefix[i]>='a' && prefix[i]<='z'||prefix[i]>='A' && prefix[i]<='Z'){ + s.push(string(1,prefix[i])); + } + + // if symbol is an operator + else + { + string op1=s.top(); + s.pop(); + string op2=s.top(); + s.pop(); + string temp=(op1+op2+prefix[i]); + s.push(temp); + } + } + // returning element at top of stack + return s.top(); +} + +// MAIN FUNCTION +int main() +{ + string exp; + cout<<"Enter expression: "; + cin>>exp; + cout<<"Prefix to Postfix expression is: "< Date: Mon, 7 Feb 2022 11:09:25 -0400 Subject: [PATCH 09/91] docs: add Turkish language reference --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index cce11a1e..93b537bb 100644 --- a/README.md +++ b/README.md @@ -14,6 +14,7 @@ Data structure and Algorithm (DSA) ## Explanations - [English](./docs/en) - [Português](.docs/pt) +- [Turkish](.docs/tr) - [繁體中文](./docs/zh-tw) - [日本語](./docs/ja) From 15dccd0a1e4254b6ac66fea103a9d486ff778b6b Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Mon, 7 Feb 2022 11:10:32 -0400 Subject: [PATCH 10/91] docs: add missing slash --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 93b537bb..3dd161e0 100644 --- a/README.md +++ b/README.md @@ -13,8 +13,8 @@ Data structure and Algorithm (DSA) ## Explanations - [English](./docs/en) -- [Português](.docs/pt) -- [Turkish](.docs/tr) +- [Português](./docs/pt) +- [Turkish](./docs/tr) - [繁體中文](./docs/zh-tw) - [日本語](./docs/ja) From 27cfae8f52ff5a9daf2ab7b16d2f6aa21cac7605 Mon Sep 17 00:00:00 2001 From: Kathy <40347043+kc0813@users.noreply.github.com> Date: Wed, 9 Feb 2022 20:16:40 -0500 Subject: [PATCH 11/91] chore(Python): add first in first out queue (#691) --- algorithms/Python/README.md | 2 + algorithms/Python/queues/fifo-queue.py | 65 ++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 algorithms/Python/queues/fifo-queue.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 282dee29..da6ca875 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -69,3 +69,5 @@ - [Binary Tree](trees/binary_tree.py) - [Binary Search Tree](trees/binary_search_tree.py) +## Queues +- [First in First out Queue](queues/fifo-queue.py) \ No newline at end of file diff --git a/algorithms/Python/queues/fifo-queue.py b/algorithms/Python/queues/fifo-queue.py new file mode 100644 index 00000000..7ddf7ad1 --- /dev/null +++ b/algorithms/Python/queues/fifo-queue.py @@ -0,0 +1,65 @@ +class FIFOqueue: + + def __init__(self, item = 0) -> None: + """ + creates the FIFOqueue object given an item, + will default to 0 if no item is passed. + + firstNum: any + """ + self.arr = [item] + + + def enqueue(self, n) -> None: + """ + adds n to the end of the queue in O(1) time + + n: Any + """ + self.arr.append(n) + + def dequeue(self): + """ + removes the first element from the queue and returns it in O(1) time + """ + return self.arr.pop(0) + + def front(self): + """ + returns the first element of the queue in O(1) time + """ + return self.arr[0] + + def rear(self): + """ + returns the last element of the queue in O(1) time + """ + return self.arr[-1] + +# main +if __name__ == '__main__': + exampleFIFO = FIFOqueue(1) + # now our queue should look like [1] after initialization + print(f"queue after initialization: {exampleFIFO.arr}") + + exampleFIFO.enqueue(5) + # now our queue should look like [1, 5] + print(f"queue after enqueueing 5: {exampleFIFO.arr}") + + print(f"If we dequeue, we are removing {exampleFIFO.dequeue()} from the queue") + # now our queue should look like [5] + print(f"queue after dequeue: {exampleFIFO.arr}") + + exampleFIFO.enqueue(7) + # now our queue should look like [5, 7] + print(f"queue after enqueueing 7: {exampleFIFO.arr}") + + exampleFIFO.enqueue(8) + # now our queue should look like [5, 7, 8] + print(f"queue after enqueueing 8: {exampleFIFO.arr}") + + # front + print(f"If we try looking at the front of the queue we get: {exampleFIFO.front()}") + + #rear + print(f"If we try looking at the rear of the queue we get: {exampleFIFO.rear()}") \ No newline at end of file From 7b07f177b91e6ec8706f7c725f4d130a24ffea8e Mon Sep 17 00:00:00 2001 From: Soumya Shankar Banerjee Date: Tue, 22 Feb 2022 00:58:28 +0530 Subject: [PATCH 12/91] enh(Python): add insert end function on singly linked list (#700) Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- algorithms/Python/linked_lists/singly.py | 55 ++++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/algorithms/Python/linked_lists/singly.py b/algorithms/Python/linked_lists/singly.py index 270a2145..6a1ade3b 100644 --- a/algorithms/Python/linked_lists/singly.py +++ b/algorithms/Python/linked_lists/singly.py @@ -78,6 +78,58 @@ class LinkedList: raise IndexError("pop from empty LinkedList") self.head = node.next return node.data + + def insertEnd(self, data): + ''' + Insert node at the end of linked list + ''' + node = Node(data) + if self.head is None: + self.head = node + return + + # Linked list traversal + temp = self.head + while(temp.next is not None): + temp = temp.next + + temp.next = node + return + + def deleteData(self, data): + ''' + Delete first occurrence of given data + ''' + temp = self.head + + # raise exception if linked list is empty + if temp is None: + raise Exception("Linked List is empty") + + # if head node is deleted + if temp.data == data: + self.head = temp.next + temp = None + return + + # search for data + # previous node data is stored + while(temp): + found = False + if temp.data == data: + found = True + break + prev = temp + temp = temp.next + + # raise exception if data not found + if not found: + raise Exception("Data not present") + + # delete the link + prev.next = temp.next + temp = None + return if __name__ == '__main__': @@ -86,5 +138,8 @@ if __name__ == '__main__': ll.push('xyz') ll.push(1.1) ll.pop() + ll.insertEnd('END') + print(ll) + ll.deleteData(1) print(ll) print(list(ll)) From e1f258ce044ee172c873d728cdcb125afb57fc9e Mon Sep 17 00:00:00 2001 From: ANUJ BISHT Date: Wed, 23 Feb 2022 18:43:42 +0530 Subject: [PATCH 13/91] chore(C): add largestElement in array (#705) --- algorithms/C/README.md | 1 + algorithms/C/arrays/largestElement.c | 62 ++++++++++++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 algorithms/C/arrays/largestElement.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 77a27dbe..da034e96 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -6,6 +6,7 @@ - [Unique Elements in an array](arrays/unique-elements-in-an-array.c) - [Reverse an array](arrays/reverse-array.c) - [Maximum difference](arrays/maximum-difference.c) +- [Largest Element](arrays/largestElement.c) ## Bit Manipulation diff --git a/algorithms/C/arrays/largestElement.c b/algorithms/C/arrays/largestElement.c new file mode 100644 index 00000000..dd3d6e9d --- /dev/null +++ b/algorithms/C/arrays/largestElement.c @@ -0,0 +1,62 @@ +/****************************************************************************** + Program to compute the largest element in array +******************************************************************************/ +#include +#define maxSize 100 + +int main() +{ + int array[maxSize], size; + int max; + + // Scanning the size of the array + printf("Enter the size of the array: "); + scanf("%d",&size); + + // Scanning the elements of array + printf("Enter the %d elements of the array: \n",size); + for(int i=0; i max) + { + max = array[i]; + } + } + + // Printing out the result + printf("\nThe largest element of the array: %d",max); + + return 0; +} + +/****************************************************************************** + OUTPUT SAMPLE +Enter the size of the array: 5 +Enter the 5 elements of the array: +Element [0]: 1 +Element [1]: 2 +Element [2]: 3 +Element [3]: 4 +Element [4]: 6 +The input array: +1 2 3 4 6 +The largest element of the array: 6 + +******************************************************************************/ From 825685dcceb6f98835b5663fd60fcf450bb10732 Mon Sep 17 00:00:00 2001 From: Aarushi Maurya Date: Wed, 23 Feb 2022 18:44:56 +0530 Subject: [PATCH 14/91] chore(CPlusPlus): add fibonacci (#703) --- .../Dynamic-Programming/fibonacci.cpp | 34 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 35 insertions(+) create mode 100644 algorithms/CPlusPlus/Dynamic-Programming/fibonacci.cpp diff --git a/algorithms/CPlusPlus/Dynamic-Programming/fibonacci.cpp b/algorithms/CPlusPlus/Dynamic-Programming/fibonacci.cpp new file mode 100644 index 00000000..7f380fe4 --- /dev/null +++ b/algorithms/CPlusPlus/Dynamic-Programming/fibonacci.cpp @@ -0,0 +1,34 @@ +/* +Fibonacci series- 0,1,1,2,3,5,... +Given a number n, we have to print the nth term of the fibonacci series +Example- if n=0, the answer will be 0 + if n=1, the answer will be 1 + if n=1, the answer will be 1 (sum of 0 and 1) + if n=2, the answer will be 2 (sum of 1 and 1) + and so on.. + +Time Complexity - O(n) +Space Complexity - O(1) +*/ + +class Solution { +public: + int fib(int n) { + + if(n<2) // if n<2, i.e, if n is 0 or 1 return n because 0th term is 0 and 1th term is 1 + return n; + + int prev1=1; + int prev2=0; + + for(int i=2; i<=n; i++) + { + int curr = prev1+prev2; // the current term is sum of the two terms before it, here prev1 is (i-1)th term and prev2 is (i-2)th term + prev2=prev1; + prev1=curr; + } + + return prev1; //at the end prev1 will have the value of the nth term, so we will return it + + } +}; diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index e62faa25..425be2db 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -38,6 +38,7 @@ - [0/1-knapsack](Dynamic-Programming/01-knapsack.cpp) - [Matrix chain Multiplication](Dynamic-Programming/matrix-chain-multiplication.cpp) - [Edit Distance](Dynamic-Programming/edit-distance.cpp) +- [Fibonacci](Dynamic-Programming/fibonacci.cpp) ## Graphs From ea01662f90a6913ca6b7faa88319afefb5f8d296 Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Wed, 23 Feb 2022 09:20:55 -0400 Subject: [PATCH 15/91] docs(readme): update reviewers --- README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 3dd161e0..a032d980 100644 --- a/README.md +++ b/README.md @@ -122,8 +122,8 @@ The programming should keep the naming convention rule of each programming langu | C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7, @Ashborn-SM | | Java | @TawfikYasser, @aayushjain7 | | C# | @ming-tsai, @Waqar-107 | -| Go | @atin | -| Python | @Arsenic-ATG, @atin, @sridhar-5 | +| Go | | +| Python | @Arsenic-ATG, @sridhar-5 | | JavaScript | @ming-tsai | ## Contributors From f2ad16e1937364a60a8fe517206f802302f2e0ed Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E3=81=91=E3=81=B1?= <76763590+k2491p@users.noreply.github.com> Date: Mon, 28 Feb 2022 22:26:28 +0900 Subject: [PATCH 16/91] docs(Japanese): add bubble sort (#706) Co-authored-by: fukuda --- docs/ja/README.md | 5 +++ docs/ja/Sorting/Bubble-Sort.md | 60 ++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) create mode 100644 docs/ja/Sorting/Bubble-Sort.md diff --git a/docs/ja/README.md b/docs/ja/README.md index 9ead69dd..61480037 100644 --- a/docs/ja/README.md +++ b/docs/ja/README.md @@ -1,4 +1,9 @@ # アルゴリズム + +## ソート + +- [バブルソート](./Sorting/Bubble-Sort.md) + ## 文字列 - [回文](./Strings/Palindrome.md) diff --git a/docs/ja/Sorting/Bubble-Sort.md b/docs/ja/Sorting/Bubble-Sort.md new file mode 100644 index 00000000..a9abb6b6 --- /dev/null +++ b/docs/ja/Sorting/Bubble-Sort.md @@ -0,0 +1,60 @@ +# バブルソート + +シンキングソートとも呼ばれるバブルソートは、最もシンプルなソートアルゴリズムである。数値の順序が正しくない場合に、数値を入れ替える。最悪計算量はO(n^2)だ。 + +## ステップ + +1. 最初の要素と次の要素を比較する。 +2. 最初の要素が次の要素より大きい場合、要素を入れ替える。 +3. 選択された数字が正しい位置に来るまで2.を実行し、次の要素を比較する。 +4. ソートが完了するまで何度も繰り返されます。 + +## 例 + +初期配列 +**5 1 4 2 8** + +ソート後配列 +**1 2 4 5 8** + +ステップ +**1回目** + +- ( **5 1** 4 2 8 ) → ( **1 5** 4 2 8 ), ここで、アルゴリズムは最初の2つの要素を比較し、5 > 1なので入れ替える。 +- ( 1 **5 4** 2 8 ) → ( 1 **4 5** 2 8 ), 5 > 4なので入れ替える。 +- ( 1 4 **5 2** 8 ) → ( 1 4 **2 5** 8 ), 5 > 2なので入れ替える。 +- ( 1 4 2 **5 8** ) → ( 1 4 2 **5 8** ), これらの要素は順番通りのため(8 > 5)、アルゴリズムは入れ替えをしない。 + +**2回目** + +- ( **1 4** 2 5 8 ) → ( **1 4** 2 5 8 ) +- ( 1 **4 2** 5 8 ) → ( 1 **2 4** 5 8 ), 4 > 2なので入れ替える。 +- ( 1 2 **4 5** 8 ) → ( 1 2 **4 5** 8 ) +- ( 1 2 4 **5 8** ) → ( 1 2 4 **5 8** ) + +さて、配列はすでにソートされたが、アルゴリズムにはソートが完了したかわからない。アルゴリズムはソートが完了したことを知るために、入れ替えなしでさらにもう1回全体のチェックを必要とする。 + +**3回目** + +- ( **1 2** 4 5 8 ) → ( **1 2** 4 5 8 ) +- ( 1 **2 4** 5 8 ) → ( 1 **2 4** 5 8 ) +- ( 1 2 **4 5** 8 ) → ( 1 2 **4 5** 8 ) +- ( 1 2 4 **5 8** ) → ( 1 2 4 **5 8** ) + +## 実装 + +- [C](../../../algorithms/C/sorting/bubble-sort.c) +- [C++](../../../algorithms/CPlusPlus/Sorting/bubble-sort.cpp) +- [CSharp](../../../algorithms/CSharp/src/Sorts/bubble-sort.cs) +- [Go](../../../algorithms/Go/sorting/bubble-sort.go) +- [Java](../../../algorithms/Java/sorting/bubble-sort.java) +- [JavaScript](../../../algorithms/JavaScript/src/sorting/bubble-sort.js) +- [Python](../../../algorithms/Python/sorting/bubble_sort.py) + +## 動画のURL + +[Youtube Video about Bubble Sort](https://www.youtube.com/watch?v=Jdtq5uKz-w4&ab_channel=mycodeschool) + +## その他 + +[Wikipedia](https://en.wikipedia.org/wiki/Bubble_sort) From 1b5bd0b1ebf9ff13723da5e05b9cd67538cda6a4 Mon Sep 17 00:00:00 2001 From: ryanoliverdev <63882612+ryanoliverdev@users.noreply.github.com> Date: Mon, 28 Feb 2022 07:30:01 -0600 Subject: [PATCH 17/91] chore(CPlusPlus): add sum of right leaves in binary tree (#689) --- algorithms/CPlusPlus/README.md | 1 + .../CPlusPlus/Trees/sum-of-right-leaves.cpp | 81 +++++++++++++++++++ 2 files changed, 82 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/sum-of-right-leaves.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 425be2db..314e0019 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -139,6 +139,7 @@ - [Finding the elements of a tree visible from top view](Trees/Top-View-Of-A-Tree.cpp) - [Binary Tree Implementation](Trees/binary-tree-implementation.cpp) - [Iterative Segment Tree](Trees/IterativeSegmentTree.cpp) +- [Sum of right leaves](Trees/sum-of-right-leaves.cpp) ## Trie diff --git a/algorithms/CPlusPlus/Trees/sum-of-right-leaves.cpp b/algorithms/CPlusPlus/Trees/sum-of-right-leaves.cpp new file mode 100644 index 00000000..99e7d6d1 --- /dev/null +++ b/algorithms/CPlusPlus/Trees/sum-of-right-leaves.cpp @@ -0,0 +1,81 @@ +// The sum of right leaves algorithm uses a queue to navigate through a binary tree +// Worst Case Time Complexity: O(n) +// Average Time Complexity: O(n) + +#include +#include + +using namespace std; + +// Node structure for tree +struct Node { + int val; + Node *left; + Node *right; + + Node(int val) { + this->val = val; + left = nullptr; + right = nullptr; + } +}; + +int sumRightLeaves(Node* root) { + queue q; + int rightSum = 0; + + // Checking if the root is nullptr push to queue if it exists + if(root) + { + q.push(root); + } + + while(!q.empty()) + { + // Check if there exists a right node + if(q.front()->right) + { + // Check if this is a leaf node + if(q.front()->right->right == nullptr && q.front()->right->left == nullptr) + { + rightSum += q.front()->right->val; + } + else + { + q.push(q.front()->right); + } + } + if(q.front()->left) // Check down left side of tree + { + q.push(q.front()->left); + } + + q.pop(); + } + + return rightSum; +} + +int main() +{ + Node* root = new Node(3); + root->left = new Node(5); + root->right = new Node(7); + root->left->left = new Node(8); + root->left->right = new Node(10); + root->right->right = new Node(13); + +// 3 +// / \ +// 5 7 +// / \ \ +// 8 10 13 +// +// Sample Output +// Sum of the right leaves: 23 + +// Outputting sum of right leaves + cout << "Sum of right leaves: " << sumRightLeaves(root); + + return 0; +} \ No newline at end of file From a1eff4fc8b6ebd7f9d7c93fcf90d45d6a2213e64 Mon Sep 17 00:00:00 2001 From: Helena He <73536278+helarious99@users.noreply.github.com> Date: Tue, 1 Mar 2022 08:01:18 -0500 Subject: [PATCH 18/91] chore(CPlusPlus): add cycle detection (#686) --- .../CPlusPlus/Graphs/cycle-detection.cpp | 87 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 88 insertions(+) create mode 100644 algorithms/CPlusPlus/Graphs/cycle-detection.cpp diff --git a/algorithms/CPlusPlus/Graphs/cycle-detection.cpp b/algorithms/CPlusPlus/Graphs/cycle-detection.cpp new file mode 100644 index 00000000..946cc551 --- /dev/null +++ b/algorithms/CPlusPlus/Graphs/cycle-detection.cpp @@ -0,0 +1,87 @@ +// Program to detect whether a graph contains a cycle. The vertices of the graph are +// placed in disjoint sets. As each edge is iterated through, the subset of the two +// vertices is determined. If the subsets are the same, then a cycle is found. +// Otherwise, the algorithm will join the two subsets together and repeat the process +// until each edge is iterated through or a cycle is found. +#include +#include +#include +#include +#include + +// Edge list implementation of unweighted, undirected graph +class Graph +{ + private: + std::vector> edgeList; + std::unordered_set uniqueVertices; // Keep track of the number of unique vertices + + public: + void insertEdge(int from, int to); + bool isCycle(); + int findSet(std::vector& parent, int i); + void unionSet(std::vector& parent, int x, int y); +}; + +void Graph::insertEdge(int from, int to) +{ + edgeList.push_back(std::make_pair(from, to)); + uniqueVertices.insert(from); + uniqueVertices.insert(to); +} + +bool Graph::isCycle() +{ + // Initialize parent vector as disjoint sets + std::vector parent(uniqueVertices.size(), -1); + + // Iterate through all graph edges + for (auto i : edgeList) + { + // Find the subset of both vertices of an edge + int x = findSet(parent, i.first); + int y = findSet(parent, i.second); + + // If the subsets are the same, then there is a cycle in the graph + if (x == y) + { + return true; + } + + unionSet(parent, x, y); + } + + return false; +} + +int Graph::findSet(std::vector& parent, int i) +{ + if (parent[i] == -1) + { + return i; + } + return findSet(parent, parent[i]); +} + +void Graph::unionSet(std::vector& parent, int x, int y) +{ + parent[x] = y; +} + +// Sample test case +// Time complexity is O(E) where E is the number of edges +int main() +{ + Graph graph; + graph.insertEdge(0, 1); + graph.insertEdge(0, 2); + graph.insertEdge(1, 2); + if (graph.isCycle()) + { + std::cout << "Graph contains a cycle" << std::endl; + } + else{ + std::cout << "Graph does not contain a cycle" << std::endl; + } + return 0; +} diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 314e0019..049f2374 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -50,6 +50,7 @@ - [Dfs traversal with recursion](Graphs/dfs-traversal.cpp) - [Connected Components](Graphs/total-connected-components.cpp) - [Dijkstra's Algorithm](Graphs/dijkstra.cpp) +- [Cycle Detection](Graphs/cycle-detection.cpp) ## Multiplication From 15d44eddaeb59460ed3c3395e1ad3095fe4ca6dd Mon Sep 17 00:00:00 2001 From: kartiknad <56294396+kartiknad@users.noreply.github.com> Date: Mon, 7 Mar 2022 07:20:41 +0530 Subject: [PATCH 19/91] chore(Python): add Rabin Karp algorithm (#699) Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- algorithms/Python/README.md | 1 + .../Python/strings/rabin-karp-algorithm.py | 98 +++++++++++++++++++ 2 files changed, 99 insertions(+) create mode 100644 algorithms/Python/strings/rabin-karp-algorithm.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index da6ca875..048c61ee 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -53,6 +53,7 @@ - [Longest Common Subsequence](strings/longest_common_subsequence.py) - [Unique Character](strings/unique_character.py) - [Add String](strings/add_string.py) +- [Rabin Karp algorithm](strings/rabin-karp-algorithm.py) ## Dynamic Programming - [Print Fibonacci Series Up To N-th Term](dynamic_programming/fibonacci_series.py) diff --git a/algorithms/Python/strings/rabin-karp-algorithm.py b/algorithms/Python/strings/rabin-karp-algorithm.py new file mode 100644 index 00000000..11eee76e --- /dev/null +++ b/algorithms/Python/strings/rabin-karp-algorithm.py @@ -0,0 +1,98 @@ +''' +String pattern matching algorithm which performs efficiently for large text and patterns + +Algorithm: +Rabin Karp works on the concept of hashing. If the substring of the given text +is same as the pattern then the corresponding hash value should also be same. Exploiting this idea +and designing a hash function which can be computed in O(m) time for both pattern and initial window +of text. The subsequent window each will require only O(1) time. And we slide the window n-m times +after the initial window. Therefore the overall complexity of calculating hash function for text is O(n-m+1) +Once the hash value matches, the underlying string is again checked with pattern for matching + + +Complexity: + Best case: O(n-m+1) + Worst case: O(nm) + + +''' + +def rabin_karp(T: str, P: str, q: int ,d: int = 256) -> None : + ''' + Parameters: + + T: string + The string where the pattern needs to be searched + + P: string + The pattern to be searched + + q: int + An appropriately chosen prime number based on length of input strings + The higher the prime number, the lower the collisions and spurious hits + + d: int, default value 256 + Denotes the no of unique character that is used for encoding + + + + + + + Example: + + >>> pos = rabin_karp("AAEXCRTDDEAAFT","AA",101) + Pattern found at pos: 0 + Pattern found at pos: 10 + + ''' + + n = len(T) # length of text + m = len(P) # length of pattern + p=0 # Hash value of pattern + t=0 # Hash value of text + + #Computing h: (h=d^m-1 mod q) + h=1 + for i in range(1,m): + h = (h*d)%q + + #Computing hash value of pattern and initial window (of size m) of text + for j in range(m): + p = (d*p + ord(P[j])) % q + t = (d*t + ord(T[j])) % q + + + found = False + pos=[] # To store positions + + #Sliding window and matching + for s in range(n-m+1): + if p==t: # if hash value matches + if P == T[s:s+m]: # check for string match + pos.append(s) + if not found: + found = True + + if s Date: Wed, 9 Mar 2022 01:28:00 +0530 Subject: [PATCH 20/91] chore(Python): add remove duplicates in list (#711) --- algorithms/Python/README.md | 3 +- .../Python/arrays/remove_duplicates_list.py | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 algorithms/Python/arrays/remove_duplicates_list.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 048c61ee..77577fc0 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -5,6 +5,7 @@ - [Majority Element](arrays/majority_element.py) - [Rotate Array](arrays/rotate_array.py) - [Missing Number](arrays/missing_number.py) +- [Remove duplicate items](arrays/remove_duplicates_list.py) ## Linked Lists - [Doubly](linked_lists/doubly.py) @@ -71,4 +72,4 @@ - [Binary Search Tree](trees/binary_search_tree.py) ## Queues -- [First in First out Queue](queues/fifo-queue.py) \ No newline at end of file +- [First in First out Queue](queues/fifo-queue.py) diff --git a/algorithms/Python/arrays/remove_duplicates_list.py b/algorithms/Python/arrays/remove_duplicates_list.py new file mode 100644 index 00000000..e2781352 --- /dev/null +++ b/algorithms/Python/arrays/remove_duplicates_list.py @@ -0,0 +1,33 @@ +""" +Algorithm Type : Array Traversal +Time Complexity : O(n) +Space Complexity : O(1) +""" + +sample_case = [0, 0, 1, 1, 1, 2, 2, 3, 3, 4] + + +def make_distinct(values: list) -> list: + """ + Remove duplicate elements in an array inplace without creating new array. + + Here, we are iterating the list backwards instead of forward because if we + remove elements in an array it will cause some issues. + + Note : Wrapped with * are sample. + """ + # *length = 10* + length = len(values) + for index in range(len(values)): + # *index_position = 0 - 10* + # *index_position = -10* + index_position = index - length + if values[index_position] in values[0:index_position]: + values.remove(values[index_position]) + + return values + + +if __name__ == "__main__": + print(make_distinct(sample_case)) + From 5abebc64eb73dc1db1584eb56f0adf9103f535ea Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Thu, 10 Mar 2022 15:49:40 -0400 Subject: [PATCH 21/91] docs: add more ignore on gitignore Add below to list *.exe .vscode/ --- .gitignore | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/.gitignore b/.gitignore index d2c52858..c15b5c75 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ Thumbs.db *.out *.class *.idea +*.exe - - +# Visual Studio Code +.vscode/ From f35e35ef5c6ced72202a0a6fadf9edf745c1e4f4 Mon Sep 17 00:00:00 2001 From: Mohanad Talat Date: Mon, 21 Mar 2022 14:51:55 +0200 Subject: [PATCH 22/91] chore(C): add radix sort (#718) --- algorithms/C/README.md | 1 + algorithms/C/sorting/radix-sort.c | 66 +++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 algorithms/C/sorting/radix-sort.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index da034e96..6caf86ae 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -53,6 +53,7 @@ - [Selection Sort](sorting/selection-sort.c) - [Quick Sort](sorting/quick-sort.c) - [Shell Sort](sorting/shell-sort.c) +- [Radix Sort](sorting/radix-sort.c) ## Strings diff --git a/algorithms/C/sorting/radix-sort.c b/algorithms/C/sorting/radix-sort.c new file mode 100644 index 00000000..6a9e3069 --- /dev/null +++ b/algorithms/C/sorting/radix-sort.c @@ -0,0 +1,66 @@ +#include + + +int get_max( int arr[], int n){ + + int myMax = -1 ; + for(int i=0; i myMax)myMax = arr[i] ; + } + + return myMax ; +} + +void count_sort(int arr[], int n, int digit){ + int count[10] = {0} ; + int *sorted ; + sorted = (int*)malloc(n * sizeof(int)); + + for(int i=0; i=0; i--){ + sorted[--count[(arr[i]/digit)%10]] = arr[i] ; + } + + for(int i=0; i Date: Thu, 24 Mar 2022 15:12:56 +0100 Subject: [PATCH 23/91] chore(C): add odd or even number (#719) Co-authored-by: LuigiAltamura --- algorithms/C/README.md | 1 + algorithms/C/maths/odd-or-even-number.c | 32 +++++++++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 algorithms/C/maths/odd-or-even-number.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 6caf86ae..a1188256 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -34,6 +34,7 @@ - [Palindrome Number](maths/palindrome.c) - [Fibonacci Series](maths/fibonacci-series.c) +- [Odd or Even Number](maths/odd-or-even-number.c) ## Queues diff --git a/algorithms/C/maths/odd-or-even-number.c b/algorithms/C/maths/odd-or-even-number.c new file mode 100644 index 00000000..2cd3553b --- /dev/null +++ b/algorithms/C/maths/odd-or-even-number.c @@ -0,0 +1,32 @@ +/** + *This program checks if a number is odd or even. + * + * Odd numbers are whole numbers that cannot be divided exactly by 2. If the number is not divisible by 2 entirely, + * it'll leave a remainder 1. + * Even numbers are whole numbers that can be divided exactly by 2. If we divide the number by 2, it'll leave a remander 0. + * + * Complexity -> O(1) + * _______________________________ + * | INPUT | OUTPUT | + * | 2 | It's an even number! | + * | 1 | It's an odd number! | + * | 3 | It's an odd number! | + * _______________________________ +* */ + +#include + +int main() +{ + int n; + printf("Enter a number:\n"); + scanf("%d", &n); + + if(n % 2 == 0 ){ + printf("It's an even number!"); + }else{ + printf("It's an odd number!"); + } + + return 0; +} \ No newline at end of file From b7fa62ce5d7a889c1a6f05381a18137949f56cdb Mon Sep 17 00:00:00 2001 From: makrandbhonde <60532803+makrandbhonde@users.noreply.github.com> Date: Tue, 29 Mar 2022 00:08:37 +0530 Subject: [PATCH 24/91] chore(Python): add program to print middle node element of linked list (#716) --- algorithms/Python/README.md | 2 + .../linked_lists/middle-node-linkedlist.py | 43 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 algorithms/Python/linked_lists/middle-node-linkedlist.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 77577fc0..4e132715 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -11,6 +11,8 @@ - [Doubly](linked_lists/doubly.py) - [Singly](linked_lists/singly.py) - [Reverse List](linked_lists/reverse-linkedlist.py) +- [Middle Node](linked_lists/middle-node-linkedlist.py) + ## Dictionaries - [Two Sum](dictionaries/two-sum.py) diff --git a/algorithms/Python/linked_lists/middle-node-linkedlist.py b/algorithms/Python/linked_lists/middle-node-linkedlist.py new file mode 100644 index 00000000..e84f50f9 --- /dev/null +++ b/algorithms/Python/linked_lists/middle-node-linkedlist.py @@ -0,0 +1,43 @@ +#printing middle node element of linked list +#we are using two pointer method to get the solution + +class Node: + #Constructor to build node + def __init__(self, data): + self.data = data + self.next = None + +class LinkedList: + #Constructor to create head node + def __init__(self): + self.head = None + + #Function to push element at head (at beginning) + def push(self, data): + new_node = Node(data) + new_node.next = self.head + self.head = new_node + + #Function returns data of middle node + def middle_element(self): + if self.head is None: + return None + slow = self.head + fast = self.head + while fast and fast.next: + slow = slow.next + fast = fast.next.next + return slow.data + +if __name__=='__main__': + ob = LinkedList() + ob.push(5) + ob.push(4) + ob.push(3) + ob.push(2) + ob.push(1) + print(ob.middle_element()) + + #list: 1->2->3->4->5 Hence middle element is 3 + + From 6d91e800be71e8b154eae12622492f8bd04fdf9c Mon Sep 17 00:00:00 2001 From: Nokhalal Mahato Date: Tue, 29 Mar 2022 18:15:50 +0530 Subject: [PATCH 25/91] chore(CPlusPlus): add number system (#714) Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- .../Number system/binary_addition.cpp | 85 +++++++++++++++++++ .../Number system/binary_to_decimal.cpp | 18 ++++ .../Number system/decimal_to_binary.cpp | 24 ++++++ .../Number system/decimal_to_hexa.cpp | 29 +++++++ .../Number system/decimal_to_octal.cpp | 24 ++++++ .../Number system/hexa_to_decimal.cpp | 24 ++++++ .../Number system/octal_to_decimal.cpp | 20 +++++ algorithms/CPlusPlus/README.md | 11 +++ 8 files changed, 235 insertions(+) create mode 100644 algorithms/CPlusPlus/Number system/binary_addition.cpp create mode 100644 algorithms/CPlusPlus/Number system/binary_to_decimal.cpp create mode 100644 algorithms/CPlusPlus/Number system/decimal_to_binary.cpp create mode 100644 algorithms/CPlusPlus/Number system/decimal_to_hexa.cpp create mode 100644 algorithms/CPlusPlus/Number system/decimal_to_octal.cpp create mode 100644 algorithms/CPlusPlus/Number system/hexa_to_decimal.cpp create mode 100644 algorithms/CPlusPlus/Number system/octal_to_decimal.cpp diff --git a/algorithms/CPlusPlus/Number system/binary_addition.cpp b/algorithms/CPlusPlus/Number system/binary_addition.cpp new file mode 100644 index 00000000..c75918af --- /dev/null +++ b/algorithms/CPlusPlus/Number system/binary_addition.cpp @@ -0,0 +1,85 @@ +#include +using namespace std; + +int reverse(int n){ + int ans=0,d; + while(n>0){ + d=n%10; + ans=ans*10 + d; + n=n/10; + } + return ans; +} + +int binary_addition(int a,int b){ + int add=0,carry=0; + while(a>0 && b>0){ + + if(a%2==1 && b%2==1){ + add=add*10 + carry; + carry=1; + } + else if((a%2==1 && b%2==0) || (a%2==0 && b%2==1)){ + if(carry==1){ + add=add*10 + 0; + carry=1; + } + else{ + add=add*10 + 1; + carry=0; + } + } + else{ + add = add*10 + carry; + carry=0; + } + a=a/10; + b=b/10; + } + while(a>0){ + if(a%2==1){ + if(carry==1){ + carry=1; + add=add*10+0; + } + else{ + carry=0; + add=add*10 + 1; + } + } + else{ + add=add*10 +carry; + carry=0; + } + a=a/10; + } + while(b>0){ + if(b%2==1){ + if(carry==1){ + carry=1; + add=add*10+0; + } + else{ + carry=0; + add=add*10 + 1; + } + } + else{ + add=add*10 +carry; + carry=0; + } + b=b/10; + } + if(carry==1){ + add=add*10 +1; + } + add=reverse(add); + return add; +} + +int main(){ + int a,b; + cin>>a>>b; + int add=binary_addition(a,b); + cout< +using namespace std; +int binarytodecimal(int n){ + int two=1,r,num=0; + while(n>0){ + r=n%10; + num=num + two*r; + two*=2; + n/=10; + } + return num; +} +int main(){ + int n; + cin>>n; + int decimal=binarytodecimal(n); + cout< +using namespace std; + +int decimaltobinary(int n){ + int max=1; + while(max<=n){ + max=max*2; + } + max/=2; + int num=0; + while(max>=1){ + num=num*10 + n/max; + n-=max*(n/max); + max=max/2; + } + return num; +} + +int main(){ + int n; + cin>>n; + int binary=decimaltobinary(n); + cout< +using namespace std; + +string decimal_to_hexa(int n){ + int multiplier=1; + while(multiplier<=n) + multiplier*=16; + multiplier/=16; + string num=""; + int d; + while(multiplier>=1){ + d=n/multiplier; + if(d>9){ + char c='A'+(d-10); + num= num + c; + } + else + num=num + to_string(d); + n=n-(d*multiplier); + multiplier/=16; + } + return num; +} +int main(){ + int n; + cin>>n; + string hexa=decimal_to_hexa(n); + cout< +using namespace std; + +int decimal_to_octal(int n){ + int multiplier=1; + while(multiplier<=n){ + multiplier*=8; + } + + multiplier/=8; + int num=0; + while(multiplier>=1){ + num=num*10 + n/multiplier; + n=n - multiplier*(n/multiplier); + multiplier/=8; + } + return num; +} +int main(){ + int n; + cin>>n; + int octal=decimal_to_octal(n); + cout< +using namespace std; + +int hexa_to_decimal(string n){ + int l=n.size(); + l=l-1; + int ans=0,x=1; + while(l>=0){ + if(n[l]>='0' && n[l]<='9') + ans+=(n[l]-'0')*x; + else + ans+=x*(n[l]-'A'+10); + x*=16; + l--; + } + return ans; +} + +int main(){ + string s; + cin>>s; + int decimal=hexa_to_decimal(s); + cout< +using namespace std; + +int octal_to_decimal(int n){ + int num=0,r,multiplier=1; + while(n>0){ + r=n%10; + num=num + (r*multiplier); + n=n/10; + multiplier=multiplier*8; + } + return num; +} + +int main(){ + int n; + cin>>n; + int decimal=octal_to_decimal(n); + cout< Date: Sat, 2 Apr 2022 00:30:29 +0530 Subject: [PATCH 26/91] chore(CPlusPlus): add print all nodes at a level on trees (#696) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Co-authored-by: Rahul Rajeev Pillai <66192267+Ashborn-SM@users.noreply.github.com> --- algorithms/CPlusPlus/README.md | 1 + .../Trees/print-all-nodes-at-a-level.cpp | 83 +++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 algorithms/CPlusPlus/Trees/print-all-nodes-at-a-level.cpp diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 73e0442e..c545fa88 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -140,6 +140,7 @@ - [Finding the elements of a tree visible from top view](Trees/Top-View-Of-A-Tree.cpp) - [Binary Tree Implementation](Trees/binary-tree-implementation.cpp) - [Iterative Segment Tree](Trees/IterativeSegmentTree.cpp) +- [Print all nodes at level k](Trees/print-all-nodes-at-a-level.cpp) - [Sum of right leaves](Trees/sum-of-right-leaves.cpp) ## Trie diff --git a/algorithms/CPlusPlus/Trees/print-all-nodes-at-a-level.cpp b/algorithms/CPlusPlus/Trees/print-all-nodes-at-a-level.cpp new file mode 100644 index 00000000..09f35a7a --- /dev/null +++ b/algorithms/CPlusPlus/Trees/print-all-nodes-at-a-level.cpp @@ -0,0 +1,83 @@ +/* Description - We have to print all nodes at a level 'k' of the tree. + +For example- If we are given the following tree, the nodes at level 1 are 1, nodes at level 2 are 2,3, nodes at level 3 are 7, 9 and nodes at level 4 are 21 and 11. +(Note- The level starts from 1, i.e root is at level 1) + + 1 level 1 + / \ + 2 3 level 2 + / \ + 7 9 level 3 + / \ + 21 11 level 4 +*/ + +#include +using namespace std; + +typedef struct Node +{ + int data; + struct Node* left; + struct Node* right; + + Node(int val) + { + data= val; + left=right=NULL; + } +}node; + +//function for level order traversal +void levelorder(Node* root, int k) +{ + if(root==NULL) + return; + + queue q; + + q.push(root); + int count=0; //for calculating at which level we are. + + while(!q.empty()) + { + count++; //increment the value of count as level is incremented + int n=q.size(); + + for(int i=0; idata<<" "; + } + if(temp->left!=NULL){ + q.push(temp->left); + } + if(temp->right!=NULL){ + q.push(temp->right); + } + } + } +} + +//main function +int main() +{ + node*root=new node(1); + root->left=new node(2); + root->right=new node(3); + root->right->left=new node(7); + root->right->right=new node(9); + root->right->left->left=new node(21); + root->right->right->right=new node(11); + + int k = 3; // here we have taken k=3 (third level of tree) + + levelorder(root,k); //calling level order function +} + +// The output of the above program will be 7 9. Since k=3 and nodes at level 3 are 7 and 9. + +// Time Complexity: O(n) where n is the number of nodes in the binary tree +// Space Complexity: O(n) where n is the number of nodes in the binary tree From 158d8c0d49ac8ce7784afc07438d60bdc552e132 Mon Sep 17 00:00:00 2001 From: Shivam Patel <87613778+ShivamPatel-24@users.noreply.github.com> Date: Mon, 4 Apr 2022 08:42:55 -0400 Subject: [PATCH 27/91] enh(CPlusPlus): add helps function on kruskal algorithm (#731) Co-authored-by: Shivam Patel --- .../CPlusPlus/Graphs/kruskal-algorithm.cpp | 28 +++++++++---------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/algorithms/CPlusPlus/Graphs/kruskal-algorithm.cpp b/algorithms/CPlusPlus/Graphs/kruskal-algorithm.cpp index 70532e1b..7fa17120 100644 --- a/algorithms/CPlusPlus/Graphs/kruskal-algorithm.cpp +++ b/algorithms/CPlusPlus/Graphs/kruskal-algorithm.cpp @@ -129,6 +129,14 @@ void KruskalMST(Graph* graph) << endl; } +// Helper function which takes in src, dest, weight, index, address of graph as an argument +// to update the value of graph for respective index +void updateGraph(int s, int d, int w, int idx, Graph** graph){ + graph->edge[idx].src = s; + graph->edge[idx].dest = d; + graph->edge[idx].weight = w; +} + // Driver code int main() { @@ -139,29 +147,19 @@ int main() Graph* graph = createGraph(V, E); // add edge 0-1 - graph->edge[0].src = 0; - graph->edge[0].dest = 1; - graph->edge[0].weight = 10; + updateGraph(0, 1, 10, 0, &graph); // add edge 0-2 - graph->edge[1].src = 0; - graph->edge[1].dest = 2; - graph->edge[1].weight = 6; + updateGraph(0, 2, 6, 1, &graph); // add edge 0-3 - graph->edge[2].src = 0; - graph->edge[2].dest = 3; - graph->edge[2].weight = 5; + updateGraph(0, 3, 5, 2, &graph); // add edge 1-3 - graph->edge[3].src = 1; - graph->edge[3].dest = 3; - graph->edge[3].weight = 15; + updateGraph(1, 3, 15, 3, &graph); // add edge 2-3 - graph->edge[4].src = 2; - graph->edge[4].dest = 3; - graph->edge[4].weight = 4; + updateGraph(2, 3, 4, 4, &graph); From 2c22117eb2215ebafa5d109418d77ae6e7c4b716 Mon Sep 17 00:00:00 2001 From: Mohammadreza Heidari Date: Thu, 7 Apr 2022 17:27:12 +0300 Subject: [PATCH 28/91] chore(CSharp): add minima maxima (#730) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- algorithms/CSharp/README.md | 1 + algorithms/CSharp/src/Search/minima-maxima.cs | 100 ++++++++++++++++++ .../CSharp/test/Search/minima-maxima.cs | 25 +++++ 3 files changed, 126 insertions(+) create mode 100644 algorithms/CSharp/src/Search/minima-maxima.cs create mode 100644 algorithms/CSharp/test/Search/minima-maxima.cs diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 821ca8b1..4488b595 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -26,6 +26,7 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/ ## Search - [Binary Search](src/Search/binary-search.cs) - [Linear Search](src/Search/linear-search.cs) +- [Minima Maxima](src/Search/minima-maxima.cs) ## Maths - [Abundant Number](src/Maths/abundant-number.cs) diff --git a/algorithms/CSharp/src/Search/minima-maxima.cs b/algorithms/CSharp/src/Search/minima-maxima.cs new file mode 100644 index 00000000..8d652260 --- /dev/null +++ b/algorithms/CSharp/src/Search/minima-maxima.cs @@ -0,0 +1,100 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace Algorithms.Search +{ + public class MinimaMaxima + { + public static void Main() + { + var numbers = new List + { + 3,1,2,5,6,7,4,6,9,10 + }; + + var minimas = FindMinimas(numbers); + var maximas = FindMaximas(numbers); + + foreach (var minima in minimas) + { + Console.WriteLine($"Local Minima: {minima}"); + } + + foreach (var maxima in maximas) + { + Console.WriteLine($"Local Maxima: {maxima}"); + } + } + + public static List FindMinimas(List numbers) + { + var result = new List(); + + if (numbers.Count < 3) + { + result.Add(numbers.Min()); + } + else + { + // Check first element + if (numbers[0] < numbers[1]) + { + result.Add(numbers[0]); + } + + //Loop middle elements + for (int i = 1; i < numbers.Count - 1; i++) + { + if (numbers[i - 1] >= numbers[i] && numbers[i] <= numbers[i + 1]) + { + result.Add(numbers[i]); + } + } + + //Check last elements + if (numbers[^1] < numbers[^2]) + { + result.Add(numbers[^1]); + } + } + + return result; + } + + public static List FindMaximas(List numbers) + { + var result = new List(); + + if (numbers.Count < 3) + { + result.Add(numbers.Max()); + } + else + { + // Check first element + if (numbers[0] > numbers[1]) + { + result.Add(numbers[0]); + } + + //Loop middle elements + for (int i = 1; i < numbers.Count - 1; i++) + { + if (numbers[i - 1] <= numbers[i] && numbers[i] >= numbers[i + 1]) + { + result.Add(numbers[i]); + } + } + + //Check last elements + if (numbers[^1] > numbers[^2]) + { + result.Add(numbers[^1]); + } + } + + return result; + } + } +} diff --git a/algorithms/CSharp/test/Search/minima-maxima.cs b/algorithms/CSharp/test/Search/minima-maxima.cs new file mode 100644 index 00000000..3c4bdc88 --- /dev/null +++ b/algorithms/CSharp/test/Search/minima-maxima.cs @@ -0,0 +1,25 @@ +using Algorithms.Search; +using NUnit.Framework; +using System.Linq; + +namespace Algorithms.Tests.Search +{ + [TestFixture] + public class MinimaMaximaTest + { + + [TestCase(new int[] { 3, 1, 2, 5, 6, 7, 4, 6, 9, 10 }, new int[] { 1, 4 })] + public void PassIntegerList_ShouldGetExpectedMinimas(int[] input, int[] result) + { + var expected1 = MinimaMaxima.FindMinimas(input.ToList()); + Assert.AreEqual(expected1, result); + } + + [TestCase(new int[] { 3, 1, 2, 5, 6, 7, 4, 6, 9, 10 }, new int[] { 3, 7, 10 })] + public void PassIntegerList_ShouldGetExpectedMaximas(int[] input, int[] result) + { + var expected1 = MinimaMaxima.FindMaximas(input.ToList()); + Assert.AreEqual(expected1, result); + } + } +} From 38a7cea7786e2e0b9a0ccf7e9b6e7ce7d3135b98 Mon Sep 17 00:00:00 2001 From: Vedant Borkar Date: Mon, 11 Apr 2022 19:00:28 +0530 Subject: [PATCH 29/91] docs: add radix sort (#736) --- docs/en/Sorting/Radix-Sort.md | 75 +++++++++++++++++++++++++++++++++++ 1 file changed, 75 insertions(+) create mode 100644 docs/en/Sorting/Radix-Sort.md diff --git a/docs/en/Sorting/Radix-Sort.md b/docs/en/Sorting/Radix-Sort.md new file mode 100644 index 00000000..2626d40c --- /dev/null +++ b/docs/en/Sorting/Radix-Sort.md @@ -0,0 +1,75 @@ +# Radix Sort + +Radix sort is a sorting algorithm that sorts the elements by first grouping the individual digits of the same place value. Then, sort the elements according to their increasing/decreasing order. + +Radix Sort's time complexity is O(n * x), where n is the size of the array and 'x' is the number of digits in the largest number. + +## Steps + +1. Finds the largest element in the array and calculates the number of digits in it. Number of digits in the largest element are calculated as it is required to go through all the significant places of all elements. + +2. Goes through each significant place one by one. + +3. Uses Counting Sort to sort the digits at each significant place. + +4. Repeats "Step-3" until it sorts the elements based on the digits at last place. + +## Example + +Given array is +``` +[ 121, 432, 564, 23, 1, 45, 788 ] +``` + +Sorted array is +``` +[ 1, 23, 45, 121, 432, 564, 788 ] +``` + + +**FIRST PASS** + +- Sorts the elements based on the unit place digits. + +![image](https://user-images.githubusercontent.com/93431609/161891635-8edf89ec-2ca7-43b5-95ca-23b75f5846bb.png) + +After first pass array looks like.. +``` +[ 121, 1, 432, 23, 564, 45, 788 ] +``` + +**SECOND PASS** + +- Sorts the elements based on digits at tens place. + +![image](https://user-images.githubusercontent.com/93431609/161892564-64b20349-4064-4125-836d-adbdfb517bbd.png) + +After second pass array looks like.. +``` +[ 1, 121, 23, 432, 45, 564, 788 ] +``` + +**THIRD PASS** + +- Finally, sorts the elements based on the digits at hundreds place. + +![image](https://user-images.githubusercontent.com/93431609/161893373-3915ae95-28e9-4b02-bc35-5921b5280f84.png) + +After third pass array looks like.. +``` +[ 1, 23, 45, 121, 432, 564, 788 ] +``` + +## Implementation + +- [C](algorithms/C/sorting/radix-sort.c) +- [C++](algorithms/CPlusPlus/Sorting/radix-sort.cpp) +- [Python](algorithms/Python/sorting/radix_sort.py) + +## Video URL + +[Youtube Video about Radix Sort](https://www.youtube.com/watch?v=XiuSW_mEn7g) + +## Others + +[Wikipedia](https://en.wikipedia.org/wiki/Radix_sort) From dd601a7734764636b189a0626c9c8db942d6e080 Mon Sep 17 00:00:00 2001 From: sam chan <96338098+samchan2022@users.noreply.github.com> Date: Mon, 11 Apr 2022 21:38:45 +0800 Subject: [PATCH 30/91] chore(Python): add dutch national flag algo (#720) --- algorithms/Python/README.md | 1 + .../Python/arrays/dutch_national_flag_algo.py | 39 +++++++++++++++++++ 2 files changed, 40 insertions(+) create mode 100644 algorithms/Python/arrays/dutch_national_flag_algo.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 4e132715..3d4a1271 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -6,6 +6,7 @@ - [Rotate Array](arrays/rotate_array.py) - [Missing Number](arrays/missing_number.py) - [Remove duplicate items](arrays/remove_duplicates_list.py) +- [Dutch National Flag Algorithm](arrays/dutch_national_flag_algo.py) ## Linked Lists - [Doubly](linked_lists/doubly.py) diff --git a/algorithms/Python/arrays/dutch_national_flag_algo.py b/algorithms/Python/arrays/dutch_national_flag_algo.py new file mode 100644 index 00000000..4afcffe0 --- /dev/null +++ b/algorithms/Python/arrays/dutch_national_flag_algo.py @@ -0,0 +1,39 @@ +""" +Algorithm Type: Array sorting with 0s,1s and 2s in a single pass +Explain: To separate three different groups +Time Complexity: O(n) +Space Complexity: O(1) + + 0 0 1 1 1 ? ? ? ? 2 2 + | | | + v v v + Low Mid High + + To goal of the algo is to shrink this '?' region + wrapped by Mid and High + + > Low starts at 1 +""" + +numbers = [2, 0, 1, 1, 2, 0, 1, 2] + + +def DNFS(numbers: list) -> list: + length = len(numbers) + low = 0 + high = length - 1 + mid = 0 + while mid <= high: + if numbers[mid] == 0: + numbers[low], numbers[mid] = numbers[mid], numbers[low] + low = low + 1 + mid = mid + 1 + elif numbers[mid] == 1: + mid = mid + 1 + else: + numbers[mid], numbers[high] = numbers[high], numbers[mid] + high = high - 1 + return numbers + +if __name__ == "__main__": + print(DNFS(numbers)) From bc0569ad09eb12c7455495b991f4a35b97371eb8 Mon Sep 17 00:00:00 2001 From: Ghada AbdulWahab Date: Sat, 16 Apr 2022 20:08:02 +0200 Subject: [PATCH 31/91] chore(Python): add uniform cost search (#723) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- algorithms/Python/README.md | 1 + .../Python/searching/uniform_cost_search.py | 44 +++++++++++++++++++ 2 files changed, 45 insertions(+) create mode 100644 algorithms/Python/searching/uniform_cost_search.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 3d4a1271..2fe7de1a 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -35,6 +35,7 @@ - [Linear Search](searching/linear_search.py) - [Ternary Search](searching/ternary_search.py) - [Interpolation Search](searching/interpolation_search.py) +- [Uniform Cost Search](searching/uniform_cost_search.py) ## Sorting - [Bubble Sort](sorting/bubble_sort.py) diff --git a/algorithms/Python/searching/uniform_cost_search.py b/algorithms/Python/searching/uniform_cost_search.py new file mode 100644 index 00000000..02e10365 --- /dev/null +++ b/algorithms/Python/searching/uniform_cost_search.py @@ -0,0 +1,44 @@ +# this graph to check the algorithm +graph={ + 'S':[('A',2),('B',3),('D',5)], + 'A':[('C',4)], + 'B':[('D',4)], + 'C':[('D',1),('G',2)], + 'D':[('G',5)], + 'G':[], + } + +#to calculate the total cost of path +def path_cost(path): + total_cost=0 + for (node, cost) in path: + total_cost+=cost + return total_cost , path[-1][0] +# well sort queue items based on total path +#if two items have the same total_cost then sort by node name (alphabetically) + +# uniform cost search +def UCS(graph, start, goal): + visited=[] + queue=[[(start,0)]] + while queue: + queue.sort(key=path_cost)#sorting by cost + path=queue.pop(0)#choosing least cost + node=path[-1][0] + if node in visited: + continue + visited.append(node) + if node==goal: + return path + else: + adjacent_nodes=graph.get(node,[]) + for(node2,cost)in adjacent_nodes: + new_path=path.copy() + new_path.append((node2,cost)) + queue.append(new_path) + + +solution= UCS(graph,'S','G') +print('solution is ' , solution) +print ('cost of solution is ',path_cost(solution)[0]) + From 76d3bf22aa0f1663d5403e3c7fc5fcbbae2206f5 Mon Sep 17 00:00:00 2001 From: Ghada AbdulWahab Date: Wed, 20 Apr 2022 15:37:34 +0200 Subject: [PATCH 32/91] chore(Python): add breath-first search (#738) Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- algorithms/Python/README.md | 1 + .../Python/searching/breadth-first-search.py | 32 +++++++++++++++++++ 2 files changed, 33 insertions(+) create mode 100644 algorithms/Python/searching/breadth-first-search.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 2fe7de1a..d9f61cfc 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -36,6 +36,7 @@ - [Ternary Search](searching/ternary_search.py) - [Interpolation Search](searching/interpolation_search.py) - [Uniform Cost Search](searching/uniform_cost_search.py) +- [Breath First Search](searching/breadth-first-search.py) ## Sorting - [Bubble Sort](sorting/bubble_sort.py) diff --git a/algorithms/Python/searching/breadth-first-search.py b/algorithms/Python/searching/breadth-first-search.py new file mode 100644 index 00000000..9b55a829 --- /dev/null +++ b/algorithms/Python/searching/breadth-first-search.py @@ -0,0 +1,32 @@ +# this graph to check the algorithm +graph={ + 'S':['B','D','A'], + 'A':['C'], + 'B':['D'], + 'C':['G','D'], + 'S':['G'], +} +#function of BFS +def BFS(graph,start,goal): + Visited=[] + queue=[[start]] + while queue: + path=queue.pop(0) + node=path[-1] + if node in Visited: + continue + Visited.append(node) + if node==goal: + return path + else: + adjecent_nodes=graph.get(node,[]) + for node2 in adjecent_nodes: + new_path=path.copy() + new_path.append(node2) + queue.append(new_path) + + + + +Solution=BFS(graph,'S','G') +print('Solution is ',Solution) From e271c02e994f09a1f8f357655ec9fbc6804ca41f Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Wed, 20 Apr 2022 09:41:00 -0400 Subject: [PATCH 33/91] chore: add more ignore word --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 587eef9e..a218db99 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt" From cf36dbcc389b555ecad219fa4a841ff0e9dc2a08 Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Wed, 20 Apr 2022 09:47:15 -0400 Subject: [PATCH 34/91] chore(codespell): ignore .github folder --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index a218db99..02508cae 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./github" From 1790d56236487d3d506bbc3812ef06a9fcd0f0a8 Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Wed, 20 Apr 2022 09:51:34 -0400 Subject: [PATCH 35/91] chore(codespell): ignore .github folder --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 02508cae..ebbfd110 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./github" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github" From 09b5568315246e6553e870f36e32bf53f444b58b Mon Sep 17 00:00:00 2001 From: Matt <87787075+maty714@users.noreply.github.com> Date: Thu, 21 Apr 2022 09:38:29 -0400 Subject: [PATCH 36/91] chore(CSharp): add character limit (#740) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- algorithms/CSharp/README.md | 1 + .../CSharp/src/Strings/character-limit.cs | 50 +++++++++++++++++++ .../CSharp/test/Strings/character-limit.cs | 18 +++++++ 3 files changed, 69 insertions(+) create mode 100644 algorithms/CSharp/src/Strings/character-limit.cs create mode 100644 algorithms/CSharp/test/Strings/character-limit.cs diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 4488b595..a5cecf58 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -22,6 +22,7 @@ For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/ ## Strings - [Palindrome](src/Strings/palindrome.cs) - [Trie](src/Strings/trie.cs) +- [Character Limit](src/Strings/character-limit.cs) ## Search - [Binary Search](src/Search/binary-search.cs) diff --git a/algorithms/CSharp/src/Strings/character-limit.cs b/algorithms/CSharp/src/Strings/character-limit.cs new file mode 100644 index 00000000..b0b2719e --- /dev/null +++ b/algorithms/CSharp/src/Strings/character-limit.cs @@ -0,0 +1,50 @@ +using System; +using System.Linq; + +//Time Complexity: O(N) +namespace Algorithms.Strings +{ + public class TextHelper + { + public static void Main() + { + Console.WriteLine("Please enter a string"); + string input = Console.ReadLine(); + + while (input == "") + { + Console.WriteLine("Please enter a string"); + input = Console.ReadLine(); + } + + Console.WriteLine("Please enter the number of characters you want to show"); + string input2 = Console.ReadLine(); + + while (!input2.All(char.IsDigit) || input2.All(char.IsWhiteSpace)) + { + Console.WriteLine("The number you have entered is invalid. Please try again:"); + input2 = Console.ReadLine(); + } + + int num = Convert.ToInt32(input2); + Console.WriteLine(CharacterLimit(input, num)); + } + + //Limits the the amount of characters shown in a string. + public static string CharacterLimit(string input, int num) + { + //converts a string to a character array + char[] ch = input.ToCharArray(); + + //loops through the array from the last element to the first, and replaces each element with a "." + for (int i = ch.Count(); i > num; i--) + { + ch[i - 1] = '.'; + } + + //converts character array back to string to be returned by the method + string output = new string(ch); + return output; + } + } +} \ No newline at end of file diff --git a/algorithms/CSharp/test/Strings/character-limit.cs b/algorithms/CSharp/test/Strings/character-limit.cs new file mode 100644 index 00000000..d810182b --- /dev/null +++ b/algorithms/CSharp/test/Strings/character-limit.cs @@ -0,0 +1,18 @@ +using NUnit.Framework; + +namespace Algorithms.CSharp.Test.Strings +{ + [TestFixture] + internal class Character_Limit + { + [TestCase("Hello", "Hel..")] + [TestCase("World", "Wor..")] + [TestCase("How Ya", "How...")] + [TestCase("Doin", "Doi.")] + public void PassString_ShouldGetExpectedResult(string text, string expected) + { + string result = Algorithms.Strings.TextHelper.CharacterLimit(text, 3); + Assert.AreEqual(expected, result); + } + } +} \ No newline at end of file From b35e80dd4edb30ea783a0aaa578686141e779a6f Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Thu, 21 Apr 2022 09:41:37 -0400 Subject: [PATCH 37/91] chore(codespell): add C# tests to ignore path --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index ebbfd110..517ffee4 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github, ./algorithms/CSharp/test/" From 4a93e105a5f13641d82400316d019cf508faa67c Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Thu, 21 Apr 2022 09:43:44 -0400 Subject: [PATCH 38/91] fix: ignore path --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 517ffee4..161b18b5 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github, ./algorithms/CSharp/test/" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github/*, ./algorithms/CSharp/test/*" From 504d2f292cd88caefcb2585f33b91628839422c7 Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Thu, 21 Apr 2022 09:45:26 -0400 Subject: [PATCH 39/91] fix(codespell): the C# test ignore path --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 161b18b5..11cdd1d3 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github/*, ./algorithms/CSharp/test/*" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github, ./algorithms/CSharp/test" From aeee10f2f01c73b48b87ac7fff0c66112aec9ebc Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Thu, 21 Apr 2022 09:50:58 -0400 Subject: [PATCH 40/91] fix(codespell): C# test folder ignore path (#746) --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 11cdd1d3..31967f78 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github, ./algorithms/CSharp/test" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github,./algorithms/CSharp/test" From 6a64805e36e972f630456473d467ddfe819c4006 Mon Sep 17 00:00:00 2001 From: Valerio Cipolla <83750862+ValerioCipolla@users.noreply.github.com> Date: Sat, 30 Apr 2022 17:38:43 +0100 Subject: [PATCH 41/91] chore(Javascript): add fibonacci series (#752) * Add fibonacci series for javascript * Added doc in js readme for fibonacci series * Add user-friendly description of algorithm in comments * fix change fibs to series * fix output spelling * add time complexity --- algorithms/JavaScript/README.md | 15 ++++++++++-- algorithms/JavaScript/src/index.js | 5 +++- .../JavaScript/src/maths/fibonacci-series.js | 24 +++++++++++++++++++ 3 files changed, 41 insertions(+), 3 deletions(-) create mode 100644 algorithms/JavaScript/src/maths/fibonacci-series.js diff --git a/algorithms/JavaScript/README.md b/algorithms/JavaScript/README.md index 3034ad0d..132fc3b0 100644 --- a/algorithms/JavaScript/README.md +++ b/algorithms/JavaScript/README.md @@ -1,31 +1,42 @@ # JavaScript ## Arrays + - [Counting Inversions](src/arrays/counting-inversions.js) ## Linked Lists + - [Singly](src/linked-lists/singly.js) - [Doubly](src/linked-lists/doubly.js) ## Searching + - [Binary Search Recursive](src/searching/binary-search-recursive.js) - [Binary Search](src/searching/binary-search.js) - [Linear Search](src/searching/linear-search.js) - + ## Sorting + - [Bubble Sort](src/sorting/bubble-sort.js) - [Insertion Sort](src/sorting/insertion-sort.js) - [Merge Sort](src/sorting/merge-sort.js) - [Quick Sort](src/sorting/quick-sort.js) - [Selection Sort](src/sorting/selection-sort.js) - + ## Strings + - [Palindrome](src/strings/palindrome.js) - [Sequence](src/strings/sequence.js) ## Stacks + - [Stacks](src/stacks/stack.js) - [Two Stack](src/stacks/two-stack.js) ## Queues + - [Queue](src/queues/queue.js) + +## Maths + +- [Fibonacci Series](src/maths/fibonacci-series.js) diff --git a/algorithms/JavaScript/src/index.js b/algorithms/JavaScript/src/index.js index f85a9fe7..806026de 100644 --- a/algorithms/JavaScript/src/index.js +++ b/algorithms/JavaScript/src/index.js @@ -4,6 +4,9 @@ require('./arrays/counting-inversions'); // Linked Lists require('./linked-lists/singly'); +// Maths +require('./maths/fibonacci-series'); + // Searching require('./searching/binary-search-recursive'); require('./searching/binary-search'); @@ -22,7 +25,7 @@ require('./strings/sequence'); // Stack require('./stacks/stack'); -require('./stacks/two-stack') +require('./stacks/two-stack'); // Queue require('./queues/queue'); diff --git a/algorithms/JavaScript/src/maths/fibonacci-series.js b/algorithms/JavaScript/src/maths/fibonacci-series.js new file mode 100644 index 00000000..1321130d --- /dev/null +++ b/algorithms/JavaScript/src/maths/fibonacci-series.js @@ -0,0 +1,24 @@ +// algorithm to generate first n numbers of fibonacci series +// Time complexity: O(n) + +function fibonacci(n) { + // Initialize array 'series' + // with the first two numbers of the fibonacci series [0, 1] + const series = [0, 1]; + for (let i = 3; i <= n; i++) { + // starting from the third number, and stopping at number n + const num1 = series[series.length - 1]; + // num1 is the last number of the series + const num2 = series[series.length - 2]; + // num2 is the second-to-last number of the series + const next = num1 + num2; + // next number is the sum of the last two + series.push(next); + // add number to list + } + // return list + return series; +} + +console.log(fibonacci(10)); +// output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] From 0cc7c9467587141fd613b6263280283b5d21e09a Mon Sep 17 00:00:00 2001 From: Valerio Cipolla <83750862+ValerioCipolla@users.noreply.github.com> Date: Fri, 6 May 2022 14:01:10 +0100 Subject: [PATCH 42/91] chore(Javascript): add factorial recursion (#756) --- algorithms/JavaScript/README.md | 4 ++++ algorithms/JavaScript/src/index.js | 3 +++ .../JavaScript/src/recursion/factorial.js | 17 +++++++++++++++++ 3 files changed, 24 insertions(+) create mode 100644 algorithms/JavaScript/src/recursion/factorial.js diff --git a/algorithms/JavaScript/README.md b/algorithms/JavaScript/README.md index 132fc3b0..f20b4faa 100644 --- a/algorithms/JavaScript/README.md +++ b/algorithms/JavaScript/README.md @@ -40,3 +40,7 @@ ## Maths - [Fibonacci Series](src/maths/fibonacci-series.js) + +## Recursion + +- [Factorial](src/recursion/factorial.js) diff --git a/algorithms/JavaScript/src/index.js b/algorithms/JavaScript/src/index.js index 806026de..b15a3328 100644 --- a/algorithms/JavaScript/src/index.js +++ b/algorithms/JavaScript/src/index.js @@ -7,6 +7,9 @@ require('./linked-lists/singly'); // Maths require('./maths/fibonacci-series'); +// Recursion +require('./recursion/factorial'); + // Searching require('./searching/binary-search-recursive'); require('./searching/binary-search'); diff --git a/algorithms/JavaScript/src/recursion/factorial.js b/algorithms/JavaScript/src/recursion/factorial.js new file mode 100644 index 00000000..e3065f29 --- /dev/null +++ b/algorithms/JavaScript/src/recursion/factorial.js @@ -0,0 +1,17 @@ +// algorithm to calculate factorial of positive integer n +// Time complexity: O(n) + +function factorial(n) { + // Error handling + // if n is negative or not an integer return string with error message + if (n < 0) return 'Only positive numbers allowed'; + if (!Number.isInteger(n)) return 'Only integers allowed'; + // if n is a positive integer + // base case: we reach 0, return 1 + if (n === 0) return 1; + // until we reach 0 we keep multiplying n by the factorial of n - 1 + return n * factorial(n - 1); +} + +console.log(factorial(5)); +// output: 120 From 25e68800e40680653fc62f2e837cb0fb116b1a6f Mon Sep 17 00:00:00 2001 From: Ankit Gururani Date: Wed, 11 May 2022 03:56:33 +0530 Subject: [PATCH 43/91] docs(CSharp): grammar enhancement (#757) --- algorithms/CSharp/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index a5cecf58..44fd6457 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -1,5 +1,5 @@ # C# -For running the `.cs` file please using [.Net Finddle](https://dotnetfiddle.net/) +To run the `.cs` file, kindly use [.Net Finddle](https://dotnetfiddle.net/) ## Arrays - [Single Number](src/Arrays/single-number.cs) From 2152f16a71b411d42a026d5bd8904209edb6df2d Mon Sep 17 00:00:00 2001 From: Nibedita Chakraborty <96379756+NiviRocks@users.noreply.github.com> Date: Sun, 29 May 2022 19:37:46 +0530 Subject: [PATCH 44/91] chore(Python): add Breadth First Search for a graph (#760) --- algorithms/Python/README.md | 1 + algorithms/Python/graphs/bfs-sequence.py | 78 ++++++++++++++++++++++++ 2 files changed, 79 insertions(+) create mode 100644 algorithms/Python/graphs/bfs-sequence.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index d9f61cfc..bc9438e9 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -71,6 +71,7 @@ ## Graphs - [Simple Graph](graphs/graph.py) +- [BFS SEQUENCE](graphs/bfs-sequence.py) ## Trees - [Binary Tree](trees/binary_tree.py) diff --git a/algorithms/Python/graphs/bfs-sequence.py b/algorithms/Python/graphs/bfs-sequence.py new file mode 100644 index 00000000..d50acad1 --- /dev/null +++ b/algorithms/Python/graphs/bfs-sequence.py @@ -0,0 +1,78 @@ +""" +BFS graph using Adjecency List +----------------------------------------------------------------------------------------- +-In Breadth First Search Sequence of any graph all children of a parent node + is visited first and the children are stored in the QUEUE array and + VISITED array. +-Children of nodes in QUEUE are visited one by one and stored in the QUEUE and + VISITED as well. +-When all children of a node is visited that node is removed from the QUEUE. +-These steps are repeated till all nodes in QUEUE are exhausted. +----------------------------------------------------------------------------------------- +-VISITED array is required to check if a node is already in BFS sequence or not. +-QUEUE array is important for ensuring that all nodes and edges are visited. +------------------------------------------------------------------------------------------ +The sequence of nodes printed in every recursion is the BFS-SEQUENCE +------------------------------------------------------------------------------------------ +""" +def ShowGraph(Adj_Dict: dict[int, list[int]])->None : #displays graph + for i in Adj_Dict: + print(i,"->",Adj_Dict[i]) + return +def Display_BFS(curr:int ,Adj_Dict: dict[int, list[int]]) -> None: # displays BFS sequence + global rear + global front + print(curr,end=" ") + if curr in Adj_Dict : + if curr not in visited: + visited.append(curr) + queue.append(curr) + rear+=1 + for i in Adj_Dict[curr]: # iterate over all neighbours of curr + if i not in visited: + queue.append(i) + visited.append(i) + rear+=1 + queue[front]=-1 # all nodes adjecent to curr are visited + front+=1 + if front==rear: # no new node to visit + return + else: + Display_BFS(queue[front],Adj_Dict) # go to next node + return + +#__main__ +#Dry Run +queue: list[int]=[]#: list[int]=[] #keeps order of BFS tree +visited: list[int]=[] #: list[int]=[] #keeps visited node +# front and rear for accessing queue +front=0 +rear=0 +#g is an adjecency list in form of dictionary +g={1:[2,4],2:[4,5],4:[7,5],5:[1,3,6],6:[3,8],8:[7]} # this is directed graph +# for undirected graph each edge has to be given twice +# Eg:- edge from 1-2 input as {1:[2]} +print("Display Graph") +ShowGraph(g) +print("BFS Sequence") +Display_BFS(1,g) #passing start node +''' +--------------------------------- +OUTPUT:- +Display Graph +1 -> [2, 4] +2 -> [4, 5] +4 -> [7, 5] +5 -> [3, 1, 6] +6 -> [8, 3] +8 -> [7] +BFS Sequence +1 2 4 5 7 3 6 8 +---------------------------------- +TIME COMPLEXITY: +-O(V+E) where V and E are number + of vertices and edges in graph + respectively. +-For Adjecency List Only! +---------------------------------- +''' From bacaa04f5a30e701d9d1d6c668c9e97b1540ca90 Mon Sep 17 00:00:00 2001 From: Ankit Gupta Date: Sun, 5 Jun 2022 23:30:06 +0530 Subject: [PATCH 45/91] fix(CPlusPlus): number system links (#762) Co-authored-by: en1gm479 --- .../{Number system => Number-system}/binary_addition.cpp | 0 .../{Number system => Number-system}/binary_to_decimal.cpp | 0 .../{Number system => Number-system}/decimal_to_binary.cpp | 0 .../{Number system => Number-system}/decimal_to_hexa.cpp | 0 .../{Number system => Number-system}/decimal_to_octal.cpp | 0 .../{Number system => Number-system}/hexa_to_decimal.cpp | 0 .../{Number system => Number-system}/octal_to_decimal.cpp | 0 7 files changed, 0 insertions(+), 0 deletions(-) rename algorithms/CPlusPlus/{Number system => Number-system}/binary_addition.cpp (100%) rename algorithms/CPlusPlus/{Number system => Number-system}/binary_to_decimal.cpp (100%) rename algorithms/CPlusPlus/{Number system => Number-system}/decimal_to_binary.cpp (100%) rename algorithms/CPlusPlus/{Number system => Number-system}/decimal_to_hexa.cpp (100%) rename algorithms/CPlusPlus/{Number system => Number-system}/decimal_to_octal.cpp (100%) rename algorithms/CPlusPlus/{Number system => Number-system}/hexa_to_decimal.cpp (100%) rename algorithms/CPlusPlus/{Number system => Number-system}/octal_to_decimal.cpp (100%) diff --git a/algorithms/CPlusPlus/Number system/binary_addition.cpp b/algorithms/CPlusPlus/Number-system/binary_addition.cpp similarity index 100% rename from algorithms/CPlusPlus/Number system/binary_addition.cpp rename to algorithms/CPlusPlus/Number-system/binary_addition.cpp diff --git a/algorithms/CPlusPlus/Number system/binary_to_decimal.cpp b/algorithms/CPlusPlus/Number-system/binary_to_decimal.cpp similarity index 100% rename from algorithms/CPlusPlus/Number system/binary_to_decimal.cpp rename to algorithms/CPlusPlus/Number-system/binary_to_decimal.cpp diff --git a/algorithms/CPlusPlus/Number system/decimal_to_binary.cpp b/algorithms/CPlusPlus/Number-system/decimal_to_binary.cpp similarity index 100% rename from algorithms/CPlusPlus/Number system/decimal_to_binary.cpp rename to algorithms/CPlusPlus/Number-system/decimal_to_binary.cpp diff --git a/algorithms/CPlusPlus/Number system/decimal_to_hexa.cpp b/algorithms/CPlusPlus/Number-system/decimal_to_hexa.cpp similarity index 100% rename from algorithms/CPlusPlus/Number system/decimal_to_hexa.cpp rename to algorithms/CPlusPlus/Number-system/decimal_to_hexa.cpp diff --git a/algorithms/CPlusPlus/Number system/decimal_to_octal.cpp b/algorithms/CPlusPlus/Number-system/decimal_to_octal.cpp similarity index 100% rename from algorithms/CPlusPlus/Number system/decimal_to_octal.cpp rename to algorithms/CPlusPlus/Number-system/decimal_to_octal.cpp diff --git a/algorithms/CPlusPlus/Number system/hexa_to_decimal.cpp b/algorithms/CPlusPlus/Number-system/hexa_to_decimal.cpp similarity index 100% rename from algorithms/CPlusPlus/Number system/hexa_to_decimal.cpp rename to algorithms/CPlusPlus/Number-system/hexa_to_decimal.cpp diff --git a/algorithms/CPlusPlus/Number system/octal_to_decimal.cpp b/algorithms/CPlusPlus/Number-system/octal_to_decimal.cpp similarity index 100% rename from algorithms/CPlusPlus/Number system/octal_to_decimal.cpp rename to algorithms/CPlusPlus/Number-system/octal_to_decimal.cpp From fee85368ba015999e06e6483b4af87ab34eff0af Mon Sep 17 00:00:00 2001 From: aakgn Date: Tue, 7 Jun 2022 23:10:03 +0300 Subject: [PATCH 46/91] docs: add singly linked list (#763) * Singly Linked List Documentation * Update singly-linked-list.md --- docs/en/Lists/singly-linked-list.md | 89 +++++++++++++++++++++++++++++ 1 file changed, 89 insertions(+) create mode 100644 docs/en/Lists/singly-linked-list.md diff --git a/docs/en/Lists/singly-linked-list.md b/docs/en/Lists/singly-linked-list.md new file mode 100644 index 00000000..f9f859b5 --- /dev/null +++ b/docs/en/Lists/singly-linked-list.md @@ -0,0 +1,89 @@ +# Singly Linked List + +A linked structure is a collection of nodes storing data and links to other nodes. In this way, nodes can be located anywhere in memory, +and passing from one node of the linked structure to another is accomplished by storing the addresses of other nodes in the linked structure. + +If a node contains a data member that is a pointer to another node, then many nodes can be strung together using only one variable to access +the entire sequence of nodes. Such a sequence of nodes is the most frequently used implementation of a linked list, which is a data structure +composed of nodes, each node holding some information and a pointer to another node in the list. If a node has a link only to its successor +in this sequence, the list is called a singly linked list. + +A node includes two data members: **info** and **next**. The info member is used to store information, and this member is important to the user. +The next member is used to link nodes to form a linked list. It is an auxiliary data member used to maintain the linked list. It is indispensable +for implementation of the linked list, but less important (if at all) from the user’s perspective. + + +## Steps + +- New node is created. +- The number(data) is assigned to the info member of this node. +- null is assigned to next member of this node. +- The new node is included in the list by making the next member of the first node a pointer to the new node. + + +## Example + +Now, let us create the three-nod linked list as an example. One way to create this three-node linked list is to first generate the node for number +8(our first data), then the node for 5(our second data), and finally the node for 2(our last data). + +*pointer is represents our successor. + +- In the first step, a new Node is created + + Pointer : pointer to first node. + + pointer->info : + + pointer->next : + +- in the second step, the info member of this node is set to 8, and, the node’s next member is set to null. + + pointer : pointer to first node. + + pointer->info : 8 + + pointer->next : null + +- in the third step, new node is created and the info member of this node is set to 5, and, the node’s next member is set to null. + + pointer : pointer to first node. + + pointer->info : 8 + + pointer->next : pointer to next node. + + Pointer->next->info : 5 + + Pointer->next->next : null + +- in the fourth step, new node is created and the info member of this node is set to 2, and, the node’s next member is set to null. + + pointer : pointer to first node. + + pointer->info : 8 + + pointer->next : pointer to next node. + + Pointer->next->info : 5 + + pointer->next->next : pointer to next node. + + pointer->next->next->info : 2 + + pointer->next->next->next : null + +## Implementation + +- [C++](../../../algorithms/CPlusPlus/Linked-Lists/singly.cpp) +- [Java](../../../algorithms/Java/linked-lists/singly.java) +- [JavaScript](../../../algorithms/JavaScript/src/linked-lists/singly.js) +- [Python](../../../algorithms/Python/linked_lists/singly.py) + +## Video URL + +[Watch Linear Search Implementation](https://www.youtube.com/watch?v=HB7TcYklBHY) + + +## References + +["Adam Drozdek", "Data Structures and Algorithms in C++", "Fourth Edition".](https://www.ebay.com/itm/Data-Structures-and-Algorithms-in-C-by-Adam-Drozdek-Fourth-Edition-/254763347609) From f1debdc7c31b4663b9a0a50f90cd40d59c5f9ff0 Mon Sep 17 00:00:00 2001 From: nohno23 <107597229+nohno23@users.noreply.github.com> Date: Sun, 3 Jul 2022 18:29:41 -0700 Subject: [PATCH 47/91] docs(ja): add insertion sort (#771) Co-authored-by: My Name --- docs/ja/README.md | 1 + docs/ja/Sorting/Insertion-Sort.md | 66 +++++++++++++++++++++++++++++++ 2 files changed, 67 insertions(+) create mode 100644 docs/ja/Sorting/Insertion-Sort.md diff --git a/docs/ja/README.md b/docs/ja/README.md index 61480037..27455842 100644 --- a/docs/ja/README.md +++ b/docs/ja/README.md @@ -3,6 +3,7 @@ ## ソート - [バブルソート](./Sorting/Bubble-Sort.md) +- [挿入ソート](./Sorting/Insertion-Sort.md) ## 文字列 - [回文](./Strings/Palindrome.md) diff --git a/docs/ja/Sorting/Insertion-Sort.md b/docs/ja/Sorting/Insertion-Sort.md new file mode 100644 index 00000000..91eca30a --- /dev/null +++ b/docs/ja/Sorting/Insertion-Sort.md @@ -0,0 +1,66 @@ +# 挿入ソート  + +基本挿入法とも呼ばれる挿入ソートは、シンプルで実装が容易であり、最も安定しているソートアルゴリズムである。数値が正しい場所にない場合に、その数値を正しい位置に挿入する。平均、最悪計算量は共にO(n^2)である。 + +挿入ソートを高速化したものとしてシェルソートがある。 + +## ステップ + +1. 0番目の要素と1番目の要素を比較する。 +2. 0番目の要素が1番目の要素より大きい場合、要素を入れ替える。 +3. 2番目の要素と1つ前の要素を比較する。 +4. 2番目の要素が1つ前の要素より大きい場合、要素を入れ替える。 +5. 2番目の要素が正しい位置に来るまで2.と4.を実行する。 +6. ソートが完了するまで3.から5.を何度も繰り返す。 + +## 例 + +初期配列 +**1 4 3 9 5** + +ソート後配列 +**1 3 4 5 9** + +ステップ +**1回目** + +- ( **1 4** 3 9 5 ) → ( **1 4** 3 9 5 ), ここでアルゴリズムは最初の2つの要素を比較し、順番通りのため(4 > 1), アルゴリズムは入れ替えをしない。 + +**2回目** + +- ( 1 **4 3** 9 5 ) → ( 1 **3 4** 9 5 ), 4 > 3なので入れ替える。 +- ( **1 3** 4 9 5 ) → ( **1 3** 4 9 5 ) + +ここで選択した要素が1つ前の要素よりも大きいため、アルゴリズムは選択した要素の次の要素に移る。(この配列の場合は3の次である4) + +**3回目** +- ( 1 **3 4** 9 5 ) → ( 1 **3 4** 9 5 ) + +**4回目** +- ( 1 3 **4 9** 5 ) → ( 1 3 **4 9** 5 ) + +**5回目** +- ( 1 3 4 **9 5** ) → ( 1 3 4 **5 9** ) +- ( 1 3 **4 5** 9) → ( 1 3 **4 5** 9 ) + +さて、この時点で配列はすでにソートされたが、まだ配列の最後の要素にたどり着いていない。アルゴリズムは配列の最後の要素を選択するまで続く。 + +**6回目** +- ( 1 3 4 **5 9** ) → ( 1 3 4 **5 9** ) + +## 実装 + +- [C](../../../algorithms/C/sorting/insertion-sort.c) +- [C++](../../../algorithms/CPlusPlus/Sorting/insertion-sort.cpp) +- [CSharp](../../../algorithms/CSharp/src/Sorts/insertion-sort.cs) +- [Go](../../../algorithms/Go/sorting/insertion-sort.go) +- [Java](../../../algorithms/Java/sorting/insertion-sort.java) +- [JavaScript](../../../algorithms/JavaScript/src/sorting/insertion-sort.js) + +## 動画のURL + +[Youtube Video about Insertion Sort](https://www.youtube.com/watch?v=i-SKeOcBwko) + +## その他 + +[Wikipedia](https://en.wikipedia.org/wiki/Insertion_sort) From c780f5a641f45fe0d9d62af670399852c20e8bbd Mon Sep 17 00:00:00 2001 From: Anika Kamath <87904385+anika-kamath@users.noreply.github.com> Date: Sat, 9 Jul 2022 21:01:28 +0530 Subject: [PATCH 48/91] chore(Python): add sum of n numbers using recursion (#770) --- algorithms/Python/README.md | 1 + recursive-sum-of-n-numbers.py | 12 ++++++++++++ 2 files changed, 13 insertions(+) create mode 100644 recursive-sum-of-n-numbers.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index bc9438e9..f3fb531a 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -25,6 +25,7 @@ - [Factorial](recursion/factorial.py) - [n-th Fibonacci number](recursion/nth_fibonacci_number.py) - [Recursive Insertion Sort](recursion/recursive_insertion_sort.py) +- [Recursive Sum of n numbers](recursion/recursive-sum-of-n-numbers.py) ## Scheduling - [Interval Scheduling](scheduling/interval_scheduling.py) diff --git a/recursive-sum-of-n-numbers.py b/recursive-sum-of-n-numbers.py new file mode 100644 index 00000000..9e7014ac --- /dev/null +++ b/recursive-sum-of-n-numbers.py @@ -0,0 +1,12 @@ +def recsum(n): + if n<=1: + return(n) + else: + return(n+recsum(n-1)) + +n= 15 + +if n<0: + print("Enter a positive integer") +else: + print("Sum =",recsum(n)) From 4add09632e39386c1ca4637a41e4259a4223fd87 Mon Sep 17 00:00:00 2001 From: PrathameshSahasrabuddhe <77877305+PrathameshSahasrabuddhe@users.noreply.github.com> Date: Fri, 15 Jul 2022 18:16:44 +0530 Subject: [PATCH 49/91] chore(Python): add depth first search (#775) * Added depth first search algorithm in Python and updated README.md * Added output example in Depth First Search algorithm * bug fixes * Fixed spelling mistake on line 1 (alorithm-> algorithm) * Moved the file from recursion folder to graphs folder and updated README.md Co-authored-by: Prathamesh Sahasrabuddhe --- algorithms/Python/README.md | 2 + .../Python/graphs/depth-first-search.py | 62 +++++++++++++++++++ 2 files changed, 64 insertions(+) create mode 100644 algorithms/Python/graphs/depth-first-search.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index f3fb531a..b73323e6 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -27,6 +27,7 @@ - [Recursive Insertion Sort](recursion/recursive_insertion_sort.py) - [Recursive Sum of n numbers](recursion/recursive-sum-of-n-numbers.py) + ## Scheduling - [Interval Scheduling](scheduling/interval_scheduling.py) @@ -73,6 +74,7 @@ ## Graphs - [Simple Graph](graphs/graph.py) - [BFS SEQUENCE](graphs/bfs-sequence.py) +- [Depth First Search](graphs/depth-first-search.py) ## Trees - [Binary Tree](trees/binary_tree.py) diff --git a/algorithms/Python/graphs/depth-first-search.py b/algorithms/Python/graphs/depth-first-search.py new file mode 100644 index 00000000..97a80ee5 --- /dev/null +++ b/algorithms/Python/graphs/depth-first-search.py @@ -0,0 +1,62 @@ +# A dfs algorithm in Python +# This is an algorithm for traversing a graph in depth first search manner +# It is commonly used in tree/graph traversals +# Time Complexity: O(V+E) +# Space Complexity: O(V) +# V is number of vertices and E is number of edges + +""" +Refer the following example for output +Graph 1: https://cdn.programiz.com/sites/tutorial2program/files/graph-dfs-step-0.png +Graph 2: https://static.javatpoint.com/ds/images/depth-first-search-algorithm2.png + +""" + +def dfs(edges, vis, node): + if(vis[node]!=1): + vis[node] = 1 + print(node, end = " ") + + for i in edges[node]: + if(vis[i]!=1): + dfs(edges, vis, i) + + +def main(): + """ Main Function """ + + #First example + + graph1 = [] + graph1.append([1,2,3]) + graph1.append([0,2]) + graph1.append([0,1,4]) + graph1.append([0]) + graph1.append([2]) + + vis = [] + for i in range(0,10): + vis.append(0) + + print("DFS for Graph 1 is:") + dfs(graph1, vis, 0) + + #Making visited list elements 0 for second graph + for i in range(0,10): + vis[i] = 0 + + graph2 = [] + graph2.append([1, 2, 3]) + graph2.append([3]) + graph2.append([4]) + graph2.append([5, 6]) + graph2.append([5, 7]) + graph2.append([2]) + graph2.append([]) + graph2.append([]) + + print("\n\nDFS for Graph 2 is:") + dfs(graph2, vis, 0) + +if __name__=="__main__": + main() \ No newline at end of file From 7985059f7d7543d1afda33b38fdf631a36e8e889 Mon Sep 17 00:00:00 2001 From: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Date: Wed, 20 Jul 2022 04:39:09 +0530 Subject: [PATCH 50/91] enh(CPlusPlus): add binary search (#777) Improved the code by adding the explanation of using (l + (r - l)) rather than using (l - r) while searching for the mid element. --- algorithms/CPlusPlus/Searching/binary-search.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/algorithms/CPlusPlus/Searching/binary-search.cpp b/algorithms/CPlusPlus/Searching/binary-search.cpp index 46cb09ee..0603d02e 100644 --- a/algorithms/CPlusPlus/Searching/binary-search.cpp +++ b/algorithms/CPlusPlus/Searching/binary-search.cpp @@ -7,6 +7,9 @@ int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; + //We use (l + (r - l)) rather than using (l - r) to avoid arithmetic overflow. + //Arithmetic overflow is the situation when the value of a variable increases + //beyond the maximum value of the memory location, and wraps around. // If the element is present at the middle itself if (arr[mid] == x) From bfcae851a0fadcc2197691cf5778ca331d5e5991 Mon Sep 17 00:00:00 2001 From: Rakshit Gondwal <98955085+rakshitgondwal@users.noreply.github.com> Date: Wed, 20 Jul 2022 04:41:47 +0530 Subject: [PATCH 51/91] enh(Java): add comments for binary search (#776) Improved the code by adding the explanation of using (l + (r - l)) rather than using (l - r) while searching for the mid element. --- algorithms/Java/searching/binary-search.java | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/algorithms/Java/searching/binary-search.java b/algorithms/Java/searching/binary-search.java index 519448af..db5442bf 100644 --- a/algorithms/Java/searching/binary-search.java +++ b/algorithms/Java/searching/binary-search.java @@ -5,7 +5,10 @@ class BinarySearch { int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { - int mid = l + (r - l) / 2; + int mid = l + (r - l) / 2; + //We use (l + (r - l)) rather than using (l - r) to avoid arithmetic overflow. + //Arithmetic overflow is the situation when the value of a variable increases + //beyond the maximum value of the memory location, and wraps around. // If the element is present at the // middle itself From 5d703d8170834244a923f81bf2ad9ff37f96bb4d Mon Sep 17 00:00:00 2001 From: Rusu Emanuel <92999481+Emanuel181@users.noreply.github.com> Date: Tue, 2 Aug 2022 12:38:49 -0700 Subject: [PATCH 52/91] chore(C): add sieve-of-eratosthenes (#778) --- algorithms/C/README.md | 1 + algorithms/C/arrays/sieve-of-eratosthenes.c | 161 ++++++++++++++++++++ 2 files changed, 162 insertions(+) create mode 100644 algorithms/C/arrays/sieve-of-eratosthenes.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index a1188256..0ca7c4c9 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -7,6 +7,7 @@ - [Reverse an array](arrays/reverse-array.c) - [Maximum difference](arrays/maximum-difference.c) - [Largest Element](arrays/largestElement.c) +- [Sieve of Eratosthenes](arrays/sieve-of-eratosthenes.c) ## Bit Manipulation diff --git a/algorithms/C/arrays/sieve-of-eratosthenes.c b/algorithms/C/arrays/sieve-of-eratosthenes.c new file mode 100644 index 00000000..52699b2c --- /dev/null +++ b/algorithms/C/arrays/sieve-of-eratosthenes.c @@ -0,0 +1,161 @@ +#include + +#define MAX 1000001 +int sieve[MAX]; + +/* + + Why do we use such a big number? Because we don't know how big the interval is, + we give as much freedom as possible; note that this number may not work for your + computer, and you will need to make it smaller, or if it works, you can make it bigger. + +*/ + + +/* + +[PROBLEM TO SOLVE]: Given a number "n", find all prime numbers till "n" inclusive. + + A prime number is a number which has only 2 divisors: 1 and itself. + +[EXAMPLE]: n = 22 + + -> The numbers are: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 + + -> The prime numbers are: 2 3 5 7 11 13 17 19 + +[APPROACH]: Sieve Of Eratosthenes algorithm + +[IDEA]: + + -> We have to analyze numbers from 2 to n. So, firstly, we write them down: + + 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... n + + -> Next, we will do something which is called marking. To illustrate this, I will put "*" below the numbers. + + -> We begin from 2 till n, and for every number, we mark all its multiples till n inclusive. + + -> We are at 2, so we mark 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26 and all numbers 2 * k, with k > 1 and stop when 2 * k > n. + + 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... n + * * * * * * * * * * * * + + -> We move at 3 so we mark 6, 9, 12, 15, 18, 21, 24 and all numbers 3 * k, with k > 1 and stop when 3 * k > n. + + 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 ... n + * * * * * * * * * * * * * * * + + -> We continue this process by taking every number till n and marking all its multiples till n inclusive. + + -> By the end of this algorithm, the numbers that remained unmarked are only prime numbers. + +[TIME COMPLEXITY]: + + For every i till sqrt(n), we perform n / i operations, where i is prime. + + The ecuation is: + sqrt(n) * (n/3 + n/4 + n/5 + n/6 + n/7 + ...) + = sqrt(n) * n * (1/3 + 1/4 + 1/5 + 1/6 + 1/7 + ...) + The third factor, according to Euler, grows the same as ln(ln(n)) + + So the time complexity is: O(sqrt(n) * n * ln(ln(n))). + +[SPACE COMPLEXITY]: O(n) + +*/ + + +void sieve_of_eratosthenes(unsigned long long n) +{ + sieve[0] = sieve[1] = 1; // we know that 0 and 1 are already pries so we mark them + + for (unsigned long long i = 4; i <= n; i += 2) sieve[i] = 1; // We know that every even number greater than 2 is not prime. + // We can mark in advance these numbers by beginning from 4 and + // iterating from 2 to 2. + + for (unsigned long long i = 3; i * i <= n; i += 2) // it is enough to iterate till sqrt(n) + { + // marking numbers + for (unsigned long long j = i * i; j <= n; j += 2 * i) sieve[j] = 1; // We can begin from i * i because all numbers till i * i have been already marked + // We iterate with j += 2 * i to avoid even numbers marked before + } + + /* + In Sieve of Eratosthenes, we use a global array, and global variables are + automatically initialized with 0. So we use that to our advantage instead of + manually setting all memory spaces with 0. + + + We are doing marking like this: + 0 - prime + 1 - not prime + + + Why? I know that using 1 for primes and 0 for not primes would have been more + intuitive, but declaring an array in global scope, it got initialized with 0, so + it is just a waste to overwrite all memory spaces with 1. + + */ +} + + +// Utility function to print prime numbers +void print_prime_numbers(unsigned long long n) +{ + for (unsigned long long i = 2; i <= n; ++i) + { + if (sieve[i] == 0) printf("%llu ", i); // if number is not marked (it is a prime number) we print it + } +} + + +// Driver program +int main() +{ + unsigned long long n; printf("Enter number: "); scanf("%llu", &n); + sieve_of_eratosthenes(n); + + printf("\n\nPrime numbers are:\n"); + print_prime_numbers(n); + printf("\n"); +} + + +/* + + [SAMPLE INPUT 1]: + 22 + Output: 2 3 5 7 11 13 17 19 + + [SAMPLE INPUT 2]: + 46 + Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 + + [SAMPLE INPUT 3]: + 100 + Output: 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97 + +*/ + + +/* + +[OBSERVATIONS]: + + -> Note that I used unsigned long long for variables, and operations like raising to power can + easily exceed unsigned long long, so be careful with input numbers. + + -> You can play around with #define MAX 1000000001 and #define MAX_PRIMES 100000001. Try to find + which is the maximum limit accepted by your computer. + + -> To make this algorithm space-efficient, you can change to C++ and use a vector container from the STL library like + this [vector vector_name]. Before that, include vector library like #include . That + container is not a regular one. It is a memory-optimization of template classes like vector , + which uses only n/8 bytes of memory. Many modern processors work faster with bytes because they + can be accessed directly. Template class vector works directly with bits. But these things + require knowledge about template classes, which are very powerful in C++. + + -> This algorithm can be optimized using bits operations to achieve linear time. + But ln(ln(n)) can be approximated to O(1). +*/ \ No newline at end of file From 16a16eb67ed0e65fdb1c802f72b7024867c41c3b Mon Sep 17 00:00:00 2001 From: brugner Date: Wed, 10 Aug 2022 18:16:42 -0300 Subject: [PATCH 53/91] docs(Spanish): add quick sort (#793) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- README.md | 18 +++++----- docs/es/CONTRIBUTING.md | 30 ++++++++++++++++ docs/es/Ordenamiento/Quick-Sort.md | 58 ++++++++++++++++++++++++++++++ docs/es/README.md | 9 +++++ 4 files changed, 107 insertions(+), 8 deletions(-) create mode 100644 docs/es/CONTRIBUTING.md create mode 100644 docs/es/Ordenamiento/Quick-Sort.md create mode 100644 docs/es/README.md diff --git a/README.md b/README.md index a032d980..ecb02edb 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,9 @@ Data structure and Algorithm (DSA) ## Explanations + - [English](./docs/en) +- [Español](./docs/es) - [Português](./docs/pt) - [Turkish](./docs/tr) - [繁體中文](./docs/zh-tw) @@ -117,14 +119,14 @@ The programming should keep the naming convention rule of each programming langu ## Reviewers -| Programming Language | Users | -| -------------------- | ------------------------------------------------- | -| C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7, @Ashborn-SM | -| Java | @TawfikYasser, @aayushjain7 | -| C# | @ming-tsai, @Waqar-107 | -| Go | | -| Python | @Arsenic-ATG, @sridhar-5 | -| JavaScript | @ming-tsai | +| Programming Language | Users | +| -------------------- | ------------------------------------------------ | +| C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7, @Ashborn-SM | +| Java | @TawfikYasser, @aayushjain7 | +| C# | @ming-tsai, @Waqar-107 | +| Go | | +| Python | @Arsenic-ATG, @sridhar-5 | +| JavaScript | @ming-tsai | ## Contributors diff --git a/docs/es/CONTRIBUTING.md b/docs/es/CONTRIBUTING.md new file mode 100644 index 00000000..c6d3e0a2 --- /dev/null +++ b/docs/es/CONTRIBUTING.md @@ -0,0 +1,30 @@ +# Nombre del algoritmo + +Escribe una breve descripción del algoritmo como: + +1. Complejidad temporal +2. Complejidad espacial +3. Aplicaciones +4. Nombre del creador +5. etc... + +## Pasos + +Describe el algoritmo como pasos simples, claros y entendibles. + +## Ejemplo + +Provee al algoritmo de datos de entrada de muestra. + +## Implementación + +Enlaces a sus implementaciones en lenguajes de programación. +NOTA: El enlace debe estar solo dentro de la carpeta algorithms. + +## URL del video + +Adjunta una URL a un video que explique el algoritmo. + +## Otro + +Cualquier otra información es siempre bienvenida y debería ser incluida en esta sección. diff --git a/docs/es/Ordenamiento/Quick-Sort.md b/docs/es/Ordenamiento/Quick-Sort.md new file mode 100644 index 00000000..5b2330dc --- /dev/null +++ b/docs/es/Ordenamiento/Quick-Sort.md @@ -0,0 +1,58 @@ +# Quick Sort + +1. **Complejidad temporal:** O(n^2) ocurre cuando el pivote elegido es siempre un elemento extremo (el más pequeño o el más grande). +2. **Complejidad espacial:** O(n). +3. **Aplicaciones:** Computación comercial, búsqueda de información, investigación de operaciones, simulación dirigida por eventos, cómputos numéricos, búsqueda combinatoria. +4. **Nombre del creador:** Tony Hoare + +## Pasos + +1. Considera el último elemento de la lista como pivote. +2. Define dos variables i y j. Asigna i y j al primer y último elemento de la lista. +3. Incrementa i hasta que lista[i] > pivote y luego detente. +4. Disminuye j hasta que lista[j] < pivote y luego detente. +5. Si i < j, entonces intercambia lista[i] y lista[j]. +6. Repite los pasos 3, 4 y 5 hasta que i > j. +7. Intercambia el elemento pivote con el elemento lista[j]. + +## Ejemplo + +**Dado el vector: [10, 80, 30, 90, 40, 50, 70]** + +**Pivote (último elemento) : 70** + +**1. 10 < 70 entonces i++ e intercambia(lista[i], lista[j]):** [10, 80, 30, 90, 40, 50, 70] + +**2. 80 < 70, entonces no es necesario hacer nada:** [10, 80, 30, 90, 40, 50, 70] + +**3. 30 < 70 entonces i++ e intercambia(lista[i], lista[j]):** [10, 30, 80, 90, 40, 50, 70] + +**4. 90 < 70, entonces no es necesario hacer nada:** [10, 30, 80, 90, 40, 50, 70] + +**5. 40 < 70 entonces i++ e intercambia(lista[i], lista[j]):** [10, 30, 40, 90, 80, 50, 70] + +**6. 50 < 70 entonces i++ e intercambia(lista[i], lista[j]):** [10, 30, 40, 50, 80, 90, 70] + +**7. Intercambia lista[i+1] y el pivote:** [10, 30, 40, 50, 70, 90, 80] + +**8. Aplica Quick Sort a la parte izquierda del pivote:** [10, 30, 40, 50] + +**9. Aplica Quick Sort a la parte derecha del pivote:** [70, 80, 90] + +**10. Vector ordenado:** [10, 30, 40, 50, 70, 80, 90] + +## Implementación + +- [Java](../../../algorithms/Java/sorting/quick-sort.java) +- [JavaScript](../../../algorithms/JavaScript/src/sorting/quick-sort.js) +- [Go](../../../algorithms/Go/sorting/quicksort.go) +- [C++](../../../algorithms/CPlusPlus/Sorting/quick-sort.cpp) +- [Python](../../../algorithms/Python/sorting/quicksort.py) +- [C](../../../algorithms/C/sorting/quick-sort.c) +## URL del video + +[Video de Youtube sobre Quick Sort](https://www.youtube.com/watch?v=DYmTpUfcyT8) + +## Otro + +[Wikipedia](https://es.wikipedia.org/wiki/Quicksort) diff --git a/docs/es/README.md b/docs/es/README.md new file mode 100644 index 00000000..fcd7d5f8 --- /dev/null +++ b/docs/es/README.md @@ -0,0 +1,9 @@ +# Algoritmos + +## Ordenamiento + +- [Quick Sort](./Ordenamiento/Quick-Sort.md) + +## Otro + +[Cómo agregar nueva documentación a un algoritmo?](./CONTRIBUTING.md) From d253a29f960d879f5283721d896c038dee31d4fc Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Wed, 10 Aug 2022 17:17:51 -0400 Subject: [PATCH 54/91] chore(codespell): ignore Spanish folder --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 31967f78..745b104f 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./.github,./algorithms/CSharp/test" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./docs/es,./.github,./algorithms/CSharp/test" From cef837425ce1f8c81c7329dbf6d0ecb8198f4078 Mon Sep 17 00:00:00 2001 From: Leong Teng Man <41246170+taimoon@users.noreply.github.com> Date: Thu, 11 Aug 2022 05:18:21 +0800 Subject: [PATCH 55/91] chore(C): add fibonacci algorithm (#794) --- algorithms/C/README.md | 1 + .../C/maths/fibonacci-number/.gitignore | 4 + algorithms/C/maths/fibonacci-number/Makefile | 4 + algorithms/C/maths/fibonacci-number/README.md | 59 ++++++++++++ algorithms/C/maths/fibonacci-number/src/fib.c | 92 +++++++++++++++++++ algorithms/C/maths/fibonacci-number/src/fib.h | 22 +++++ .../C/maths/fibonacci-number/src/main.c | 23 +++++ 7 files changed, 205 insertions(+) create mode 100644 algorithms/C/maths/fibonacci-number/.gitignore create mode 100644 algorithms/C/maths/fibonacci-number/Makefile create mode 100644 algorithms/C/maths/fibonacci-number/README.md create mode 100644 algorithms/C/maths/fibonacci-number/src/fib.c create mode 100644 algorithms/C/maths/fibonacci-number/src/fib.h create mode 100644 algorithms/C/maths/fibonacci-number/src/main.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 0ca7c4c9..9e241b51 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -36,6 +36,7 @@ - [Palindrome Number](maths/palindrome.c) - [Fibonacci Series](maths/fibonacci-series.c) - [Odd or Even Number](maths/odd-or-even-number.c) +- [Fibonacci Number](maths/fibonacci-number/README.md) ## Queues diff --git a/algorithms/C/maths/fibonacci-number/.gitignore b/algorithms/C/maths/fibonacci-number/.gitignore new file mode 100644 index 00000000..2441f03a --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/.gitignore @@ -0,0 +1,4 @@ +main +# binary files +*.o +*.exe \ No newline at end of file diff --git a/algorithms/C/maths/fibonacci-number/Makefile b/algorithms/C/maths/fibonacci-number/Makefile new file mode 100644 index 00000000..8214801c --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/Makefile @@ -0,0 +1,4 @@ +run: main.c + .\a.exe +main.c: + gcc .\src\main.c .\src\fib.c -lm diff --git a/algorithms/C/maths/fibonacci-number/README.md b/algorithms/C/maths/fibonacci-number/README.md new file mode 100644 index 00000000..7d5101c1 --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/README.md @@ -0,0 +1,59 @@ +# Fibonacci Number +Fibonacci numbers form a Fibonacci sequence where given any number (excluding first 2 terms) is a sum of its two preceding numbers. Usually, the sequence is either start with 0 and 1 or 1 and 1. Below is a Fibonacci sequnce starting from 0 and 1: + +$$ +0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, \dots +$$ + +The problem is to calculate the n-th term Fibonacci number given two starting numbers. + +## Prerequisites +- C compiler (or IDE) +- MAKE software (optional if you compile the source files manually) + + +## Instructions +- using makefile + ```bash + make # or mingw32-make + ``` +- compile using gcc + ``` + cd \fibonacci-number + gcc .\src\main.c + ``` +## Note +The sequence can be described by a recurrent function as below: + +$$ +\begin{align*} + F(0) &= 0 \\ + F(1) &= 1 \\ + F(n) &= F(n-1) + F(n-2) +\end{align*} +$$ + +- This provides a direct recursive implementation. The time complexity is $O(2^n)$. It can be improved through memomization. +- It can done iteratively using 2 more states variables. The time complexity is $O(n)$. +- There exists a clever logarithmic algorithm $O(\log{n})$ in computing n-th term Fibonacci number. The computations can be in form of matrix multiplication, then we can devise some form of Ancient Egyptian multiplication (i.e.: double and squaring) to improve the algorithm. [reference](https://rybczak.net/2015/11/01/calculation-of-fibonacci-numbers-in-logarithmic-number-of-steps/) +- Lastly, there also exist a formula to approximate n-term Fibonacci number $O(1)$. [reference](https://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html) + +The given implementations shall assume that the Fibonacci sequence is starting from 0 and 1. The reader may try to generalize it to certain extent as a practice. + +## Test Cases & Output + +1. Example output of calling function: +``` +/* some code */ +printf("%d", iter_fib(7)); +printf("%d\n", memo_fib(7)); +/* some code */ +``` + +``` +13 +13 +``` +2. The code should yield the same output as other version. + +3. The sum of even Fibonacci numbers below 4000000 should be 4613732. [Adapted from Project Euler.net](https://projecteuler.net/problem=2) diff --git a/algorithms/C/maths/fibonacci-number/src/fib.c b/algorithms/C/maths/fibonacci-number/src/fib.c new file mode 100644 index 00000000..41196239 --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/src/fib.c @@ -0,0 +1,92 @@ +#include"fib.h" +#include // sqrt, pow are used in binet_fib + +int recur_fib(int n){ + if(n == 0 || n == 1) + return n; + else + return recur_fib(n-1) + recur_fib(n-2); +} +int iter_fib(int n){ + if(n == 0 || n == 1) + return n; + int prev2 = 0; + int prev1 = 1; + int res = prev1 + prev2; + for(n = n - 2; n > 0; --n){ + prev2 = prev1; + prev1 = res; + res = prev1 + prev2; + } + return res; +} + +// it should be called before using the function memo_fib() +void memomizing_fib(){ + memomized_fib[0] = 0; + memomized_fib[1] = 1; + for(int i = 2; i < MAXSIZE; ++i) + memomized_fib[i] = memomized_fib[i-1]+memomized_fib[i-2]; +} + +// return memomized value if exists, or else compute it as usual +int memo_fib(int n){ + if(n < MAXSIZE && n >= 0) + return memomized_fib[n]; + else + return memo_fib(n-1) + memo_fib(n-2); +} +/** + * fibonacci based linear transformation (linear algebra) + * reference: https://rybczak.net/2015/11/01/calculation-of-fibonacci-numbers-in-logarithmic-number-of-steps/ +*/ +int iter_log_fib(int n){ + int a = 0; + int b = 1; + int p = 0; + int q = 1; + while(n > 0){ + if(n%2 == 0){ + int prev_p = p; + int prev_q = q; + p = prev_p*prev_p + prev_q*prev_q; + q = (2*prev_p + prev_q)*prev_q; + n = n/2; + } + else{ + int prev_a = a; + int prev_b = b; + --n; + a = p*prev_a + q*prev_b; + b = q*prev_a + (p+q)*prev_b; + } + } + return a; +} + +/** + * fibonacci based linear transformation (linear algebra) + * reference: https://rybczak.net/2015/11/01/calculation-of-fibonacci-numbers-in-logarithmic-number-of-steps/ +*/ +int log_fib_helper(int n, int a, int b, int p, int q){ + if(n == 0) + return a; + else if(n%2 == 0) + return log_fib_helper(n/2, a, b, p*p+q*q, (2*p+q)*q); + else + return log_fib_helper(n-1, p*a + q*b, q*a+(p+q)*b, p, q); +} + +int log_fib(int n){ + return log_fib_helper(n,0,1,0,1); +} +/** + * Closed form formula + * reference: https://mathworld.wolfram.com/BinetsFibonacciNumberFormula.html +*/ +int binet_fib(int n){ + const double golden_ratio = (1+sqrt(5))/2; + const double conjugate_golden_ratio = 1-golden_ratio; + double res = (pow(golden_ratio,n) - pow(conjugate_golden_ratio, n))/sqrt(5); + return round(res); +} diff --git a/algorithms/C/maths/fibonacci-number/src/fib.h b/algorithms/C/maths/fibonacci-number/src/fib.h new file mode 100644 index 00000000..c770d96d --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/src/fib.h @@ -0,0 +1,22 @@ +#ifndef FIB_H_INCLUDED +#define FIB_H_INCLUDED + +/** + * fib(n) takes nonnegative number n + * return n-th term fibonacci number. + * The prefix highlights its algorithm used + */ + +int recur_fib(int n); +int iter_fib(int n); + +#define MAXSIZE 30 +int memomized_fib[MAXSIZE]; +void memomizing_fib(); // it should be called before using the function memo_fib() + +int memo_fib(int n); +int iter_log_fib(int n); +int log_fib(int n); +int binet_fib(int n); + +#endif \ No newline at end of file diff --git a/algorithms/C/maths/fibonacci-number/src/main.c b/algorithms/C/maths/fibonacci-number/src/main.c new file mode 100644 index 00000000..8bc173fc --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/src/main.c @@ -0,0 +1,23 @@ +#include +#include"fib.h" + +int main(){ + memomizing_fib(); // this is to initialize the memomized table + int n = 15; + printf("%d\n", recur_fib(n)); // it becomes slow as n get larger for recur_fib + for(int i = 0; i <= 35; ++i){ + printf("n = %d\t", i); + printf(" %d", iter_fib(i)); + printf(" %d", memo_fib(i)); + printf(" %d", log_fib(i)); + printf(" %d", binet_fib(i)); + printf(" %d\n", iter_log_fib(i)); + } + int sum = 0; + int bound = 4000000; + for(int i = 0; memo_fib(i) < bound; ++i) + if(memo_fib(i)%2 == 0) + sum += memo_fib(i); + printf("The sum of even Fibonacci number below %d = %d", bound, sum); + return 0; +} From e42f4bb0b1e7f7b7413e95038eb8f9aac997e45e Mon Sep 17 00:00:00 2001 From: Ashad <93534298+Ashad001@users.noreply.github.com> Date: Thu, 11 Aug 2022 23:52:36 +0500 Subject: [PATCH 56/91] chore(CPlusPlus): add reverse number algorithm (#789) Co-authored-by: Arsenic <54987647+Arsenic-ATG@users.noreply.github.com> --- algorithms/C/maths/fibonacci-number/src/fib.c | 2 +- algorithms/C/maths/fibonacci-number/src/fib.h | 7 ++-- .../C/maths/fibonacci-number/src/main.c | 2 +- algorithms/CPlusPlus/README.md | 1 + .../CPlusPlus/Recursion/reverse-a-number.cpp | 34 +++++++++++++++++++ 5 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 algorithms/CPlusPlus/Recursion/reverse-a-number.cpp diff --git a/algorithms/C/maths/fibonacci-number/src/fib.c b/algorithms/C/maths/fibonacci-number/src/fib.c index 41196239..25ead35d 100644 --- a/algorithms/C/maths/fibonacci-number/src/fib.c +++ b/algorithms/C/maths/fibonacci-number/src/fib.c @@ -1,4 +1,4 @@ -#include"fib.h" +#include"./fib.h" // NOLINT(build/include) #include // sqrt, pow are used in binet_fib int recur_fib(int n){ diff --git a/algorithms/C/maths/fibonacci-number/src/fib.h b/algorithms/C/maths/fibonacci-number/src/fib.h index c770d96d..febadaf1 100644 --- a/algorithms/C/maths/fibonacci-number/src/fib.h +++ b/algorithms/C/maths/fibonacci-number/src/fib.h @@ -1,5 +1,6 @@ -#ifndef FIB_H_INCLUDED -#define FIB_H_INCLUDED + +#ifndef ALGORITHMS_C_MATHS_FIBONACCI_NUMBER_SRC_FIB_H_ +#define ALGORITHMS_C_MATHS_FIBONACCI_NUMBER_SRC_FIB_H_ /** * fib(n) takes nonnegative number n @@ -19,4 +20,4 @@ int iter_log_fib(int n); int log_fib(int n); int binet_fib(int n); -#endif \ No newline at end of file +#endif // ALGORITHMS_C_MATHS_FIBONACCI_NUMBER_SRC_FIB_H_" diff --git a/algorithms/C/maths/fibonacci-number/src/main.c b/algorithms/C/maths/fibonacci-number/src/main.c index 8bc173fc..7e0759db 100644 --- a/algorithms/C/maths/fibonacci-number/src/main.c +++ b/algorithms/C/maths/fibonacci-number/src/main.c @@ -1,5 +1,5 @@ #include -#include"fib.h" +#include"./fib.h" // NOLINT(build/include) int main(){ memomizing_fib(); // this is to initialize the memomized table diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index c545fa88..0350073e 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -186,6 +186,7 @@ - [Product of two numbers](Recursion\product-of-numbers.cpp) - [Product of digits in a number](Recursion\product-of-digits.cpp) - [Linear search using recursion](Recursion/linear-search.cpp) +- [Reverse a number using recursion](Recursion/reverse-a-number.cpp) ## Number System diff --git a/algorithms/CPlusPlus/Recursion/reverse-a-number.cpp b/algorithms/CPlusPlus/Recursion/reverse-a-number.cpp new file mode 100644 index 00000000..884402bc --- /dev/null +++ b/algorithms/CPlusPlus/Recursion/reverse-a-number.cpp @@ -0,0 +1,34 @@ +/* +Description: Program to reverse integer using recursion +Time complexity: O(n) where n is the number of digits in the integer +*/ + +#include +#include +using namespace std; + +int Helper(int n ,int base , int ans) +{ + if(n < 1) + return ans; + ans = ans * base + (n % 10); // Update the ans for every digit + return Helper(n / 10, base , ans); +} + +int Rev(int n) +{ + return Helper(n , 10, 0); +} + + +int main(int argc, char const *argv[]) +{ + cout << Rev(13579); + + return 0; +} +/* +Input: 13579 +Output: 97531 +*/ + From ac970481a91868b59278889ed2f2b36a6ccd068b Mon Sep 17 00:00:00 2001 From: brugner Date: Fri, 12 Aug 2022 09:39:22 -0300 Subject: [PATCH 57/91] chore(CSharp): add quick sort (#798) --- algorithms/CSharp/README.md | 12 +++ algorithms/CSharp/src/Sorts/quick-sort.cs | 93 ++++++++++++++++++++++ algorithms/CSharp/test/Sorts/quick-sort.cs | 39 +++++++++ 3 files changed, 144 insertions(+) create mode 100644 algorithms/CSharp/src/Sorts/quick-sort.cs create mode 100644 algorithms/CSharp/test/Sorts/quick-sort.cs diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 44fd6457..5f17d0b7 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -1,45 +1,57 @@ # C# + To run the `.cs` file, kindly use [.Net Finddle](https://dotnetfiddle.net/) ## Arrays + - [Single Number](src/Arrays/single-number.cs) ## Dynamic Programming + - [Longest Common Subsequence](src/Dynamic-Programming/longest-common-subsequence.cs) ## Number Theory + - [Big Mod Algorithm](src/Number-Theory/big-mod.cs) - [Sieve of Eratosthenes](src/Number-Theory/sieve-of-eratosthenes.cs) - [Bitwise Sieve of Eratosthenes](src/Number-Theory/bitwise-sieve-of-eratosthenes.cs) ## Sorts + - [Bubble Sort](src/Sorts/bubble-sort.cs) - [Insertion Sort](src/Sorts/insertion-sort.cs) - [Selection Sort](src/Sorts/selection-sort.cs) - [Counting Sort](src/Sorts/counting-sort.cs) - [Merge Sort](src/Sorts/merge-sort.cs) +- [Quick Sort](src/Sorts/quick-sort.cs) ## Strings + - [Palindrome](src/Strings/palindrome.cs) - [Trie](src/Strings/trie.cs) - [Character Limit](src/Strings/character-limit.cs) ## Search + - [Binary Search](src/Search/binary-search.cs) - [Linear Search](src/Search/linear-search.cs) - [Minima Maxima](src/Search/minima-maxima.cs) ## Maths + - [Abundant Number](src/Maths/abundant-number.cs) - [Naismith's Rule](src/Maths/naismith-rule.cs) ## Queues + - [Queue Implementation Using Two Stacks](src/Queues/queue-implementation-using-two-stacks.cs) ## Recursion + - [Factorial](src/Recursion/factorial.cs) ## Graph + - [Breadth First Search](src/Graph/breadth-first-search.cs) - [Depth First Search](src/Graph/depth-first-search.cs) - [Kruskals Algorithm to Find Minimum Spanning Tree](src/Graph/kruskals-algorithm.cs) diff --git a/algorithms/CSharp/src/Sorts/quick-sort.cs b/algorithms/CSharp/src/Sorts/quick-sort.cs new file mode 100644 index 00000000..0c95ee59 --- /dev/null +++ b/algorithms/CSharp/src/Sorts/quick-sort.cs @@ -0,0 +1,93 @@ +using System; + +namespace Algorithms.Sorts +{ + public class QuickSort + { + public static void Main() + { + int[] array = { 10, 7, 8, 9, 1, 5 }; + + Sort(array, 0, array.Length - 1); + PrintArray(array); + } + + /// + /// Sorts an array. + /// + /// Array to be sorted. + /// Starting index. + /// Ending index. + public static int[] Sort(int[] array, int low, int high) + { + if (low < high) + { + // Select a pivot + int pivot = Partition(array, low, high); + + // Sort each subarray + Sort(array, low, pivot - 1); + Sort(array, pivot + 1, high); + } + + return array; + } + + /// + /// This method takes the last element as pivot, places + /// it at its correct position in sorted array, and + /// places all smaller (smaller than pivot) + /// to left of it and all greater elements to its right. + /// + /// Array to be sorted. + /// Starting index. + /// Ending index. + /// + private static int Partition(int[] array, int low, int high) + { + int pivot = array[high]; + int i = low - 1; + + for (int j = low; j <= high - 1; j++) + { + // If current element is smaller than the pivot + if (array[j] < pivot) + { + // Increment index of smaller element and swap them + i++; + Swap(array, i, j); + } + } + + Swap(array, i + 1, high); + + return (i + 1); + } + + /// + /// Swaps two elements. + /// + /// Array to be sorted. + /// An index. + /// Another index. + private static void Swap(int[] array, int i, int j) + { + int temp = array[i]; + array[i] = array[j]; + array[j] = temp; + } + + static void PrintArray(int[] array) + { + Console.Write("Sorted array: "); + + for (int i = 0; i < array.Length; i++) + { + Console.Write($"{array[i]} "); + } + + Console.WriteLine(); + } + } +} + diff --git a/algorithms/CSharp/test/Sorts/quick-sort.cs b/algorithms/CSharp/test/Sorts/quick-sort.cs new file mode 100644 index 00000000..ade0bcf9 --- /dev/null +++ b/algorithms/CSharp/test/Sorts/quick-sort.cs @@ -0,0 +1,39 @@ +using NUnit.Framework; + +namespace Algorithms.Tests.Sorts +{ + [TestFixture] + public class QuickSort + { + static readonly object[] TestCasesForQuickSort = + { + new object[] { + new int[] { 0, 19, 12, 22, 107, 118, 0, 1, 2}, + "0, 0, 1, 2, 12, 19, 22, 107, 118" + }, + + new object[] { + new int[] { 10, 11, 19, 0, -1, -19, -12, 1, 2, 1, 16, -100}, + "-100, -19, -12, -1, 0, 1, 1, 2, 10, 11, 16, 19" + }, + + new object[] { + new int[] { -1, -2, -3, -4, -5, -10}, + "-10, -5, -4, -3, -2, -1" + }, + + new object[] { + new int[] { -1 }, + "-1" + } + }; + + [TestCaseSource(nameof(TestCasesForQuickSort))] + public void TestQuickSort_ShouldGetExpected(int[] array, string expected) + { + var results = Algorithms.Sorts.QuickSort.Sort(array, 0, array.Length - 1); + + Assert.That(expected, Is.EqualTo(string.Join(", ", results))); + } + } +} From d14ef693953bafcf65baf95fa69b373baf2d6d83 Mon Sep 17 00:00:00 2001 From: Mohit Chakraverty <79406819+mohitchakraverty@users.noreply.github.com> Date: Sat, 13 Aug 2022 00:50:58 +0530 Subject: [PATCH 58/91] docs(en): add cycle sort (#799) --- docs/en/README.md | 1 + docs/en/Sorting/Cycle-Sort.md | 91 +++++++++++++++++++++++++++++++++++ 2 files changed, 92 insertions(+) create mode 100644 docs/en/Sorting/Cycle-Sort.md diff --git a/docs/en/README.md b/docs/en/README.md index aa1b5fd4..57254776 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -8,6 +8,7 @@ - [Insertion Sort](./Sorting/Insertion-Sort.md) - [Heap Sort](./Sorting/Heap-Sort.md) - [Quick Sort](./Sorting/Quick-Sort.md) +- [Cycle Sort](./Sorting/Cycle-Sort.md) ## Strings diff --git a/docs/en/Sorting/Cycle-Sort.md b/docs/en/Sorting/Cycle-Sort.md new file mode 100644 index 00000000..e589c2ae --- /dev/null +++ b/docs/en/Sorting/Cycle-Sort.md @@ -0,0 +1,91 @@ +# Cycle Sort + +Cycle sort is a comparison sorting algorithm that forces array to be factored into the number of cycles where each of them can be rotated to produce a sorted array. It is theoretically optimal in the sense that it reduces the number of writes to the original array. +It is an in-place and unstable sorting algorithm. + +Time Complexity : O(n^2) +- Worst Case : O(n^2) +- Average Case: O(n^2) +- Best Case : O(n^2) + +Space complexity : +The space complexity is constant cause this algorithm is in place so it does not use any extra memory to sort. +Auxiliary space: O(1) + +## Steps + +Suppose there is an array **arr** with **n** distinct elements. Given an element **A**, we can find its index by counting the number of elements smaller than **A**. + +1. If the element is at its correct position, simply leave it as it is. +2. Else, we have to find the correct position of **A** by counting the number of elements smaller than it. Another element **B** is replaced to be moved to its correct position. This process continues until we get an element at the original position of **A**. + +The above-illustrated process constitutes a cycle. Repeat this cycle for every element of the list until the list is sorted. + +## Example + +arr[] = {10, 5, 2, 3} + + index = 0 1 2 3 + +cycle_start = 0 + +item = 10 = arr[0] + +Find position where we put the item + +pos = cycle_start + +i=pos+1 + +while(i < n) + +if (arr[i] < item) + + pos++; + +We put 10 at arr[3] and change item to +old value of arr[3]. + +arr[] = {10, 5, 2, 10} + +item = 3 + +Again rotate rest cycle that start with index '0' + +Find position where we put the item = 3 + +we swap item with element at arr[1] now + +arr[] = {10, 3, 2, 10} + +item = 5 + +Again rotate rest cycle that start with index '0' and item = 5 + +we swap item with element at arr[2]. + +arr[] = {10, 3, 5, 10 } + +item = 2 + +Again rotate rest cycle that start with index '0' and item = 2 + +arr[] = {2, 3, 5, 10} + +Above is one iteration for cycle_stat = 0. + +Repeat above steps for cycle_start = 1, 2, ..n-2 + +## Implementation + +- [C++](../../../algorithms/CPlusPlus/Sorting/cycle-sort.cpp) +- [Java](../../../algorithms/Java/sorting/cyclic-sort.java) +- [Python](../../../algorithms/Python/sorting/count-sort.py) + +## Video URL + +[Youtube Video about Cycle Sort](https://youtu.be/gZNOM_yMdSQ) + +## Other + +[Wikipedia](https://en.wikipedia.org/wiki/Cycle_sort) \ No newline at end of file From 6f19b452ea07ab70348ed76dd479dc7d9693be38 Mon Sep 17 00:00:00 2001 From: Hridyansh Pareek Date: Mon, 15 Aug 2022 19:33:38 +0530 Subject: [PATCH 59/91] chore(Python) : add GCD using recursion following Euclid's Algorithm (#797) --- algorithms/Python/README.md | 1 + .../Python/recursion/gcd_using_recursion.py | 23 +++++++++++++++++++ 2 files changed, 24 insertions(+) create mode 100644 algorithms/Python/recursion/gcd_using_recursion.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index b73323e6..b2be029d 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -26,6 +26,7 @@ - [n-th Fibonacci number](recursion/nth_fibonacci_number.py) - [Recursive Insertion Sort](recursion/recursive_insertion_sort.py) - [Recursive Sum of n numbers](recursion/recursive-sum-of-n-numbers.py) +- [GCD by Euclid's Algorithm](recursion/gcd_using_recursion.py) ## Scheduling diff --git a/algorithms/Python/recursion/gcd_using_recursion.py b/algorithms/Python/recursion/gcd_using_recursion.py new file mode 100644 index 00000000..092d65d8 --- /dev/null +++ b/algorithms/Python/recursion/gcd_using_recursion.py @@ -0,0 +1,23 @@ +#EUCLIDS ALGORITHM + +def gcd(a, b): + if a<0: + a = -a + if b<0: + b = -b + if b==0: + return a + else: + return gcd(b, a%b) + + +#TIME COMPLEXITY - O(log(min(a, b))) +#EXAMPLES +#print(gcd(10, 2)) -> 2 +#print(gcd(30, 15)) -> 3 +#print(gcd(-30, 15)) -> 3 +#WORKING +#We are using the Euclidean Algorithm to calculate the GCD of a number +#it states that if a and b are two positive integers then GCD or greatest common +#divisors of these two numbers will be equal to the GCD of b and a%b or +#gcd(a, b) = gcd(b, a%b) till b reaches 0 From 6e39b2bc6063d1033600d04412ee4e82baf49207 Mon Sep 17 00:00:00 2001 From: Mohit Chakraverty <79406819+mohitchakraverty@users.noreply.github.com> Date: Wed, 17 Aug 2022 20:50:07 +0530 Subject: [PATCH 60/91] enh(Java): binary search (#800) * add Cycle-Sort.md * corrected documentation * add Cycle-Sort.md * Fixed the broken link * Added the file index for Cycle-Sort * Fixed typo * created new file for iterative binary search * created binary-search.java --- algorithms/Java/searching/binary-search.java | 112 +++++++++++-------- 1 file changed, 63 insertions(+), 49 deletions(-) diff --git a/algorithms/Java/searching/binary-search.java b/algorithms/Java/searching/binary-search.java index db5442bf..21e24a1b 100644 --- a/algorithms/Java/searching/binary-search.java +++ b/algorithms/Java/searching/binary-search.java @@ -1,50 +1,64 @@ -// Java implementation of recursive Binary Search -class BinarySearch { - // Returns index of x if it is present in arr[l..r], - // else return -1 - int binarySearch(int arr[], int l, int r, int x) - { - if (r >= l) { - int mid = l + (r - l) / 2; - //We use (l + (r - l)) rather than using (l - r) to avoid arithmetic overflow. - //Arithmetic overflow is the situation when the value of a variable increases - //beyond the maximum value of the memory location, and wraps around. - - // If the element is present at the - // middle itself - if (arr[mid] == x) - return mid; - - // If element is smaller than mid, then - // it can only be present in left subarray - if (arr[mid] > x) - return binarySearch(arr, l, mid - 1, x); - - // Else the element can only be present - // in right subarray - return binarySearch(arr, mid + 1, r, x); - } - - // We reach here when element is not present - // in array - return -1; - } - - // Driver method to test above - public static void main(String args[]) - { - BinarySearch ob = new BinarySearch(); - int arr[] = { 2, 3, 4, 10, 40 }; - int n = arr.length; - int x = 10; - int result = ob.binarySearch(arr, 0, n - 1, x); - if (result == -1) - System.out.println("Element not present"); - else - System.out.println("Element found at index " + result); - } -} +// Algorithm BinarySearch Iterative method +/*binarySearch(arr, x, low, high) + repeat till low = high + mid = (low + high)/2 + if (x == arr[mid]) + return mid + + else if (x > arr[mid]) // x is on the right side + low = mid + 1 + + else // x is on the left side + high = mid - 1 + */ +// Time Complexity : O(log(n)) -// For running in terminal rename this file to BinarySearch.java -//then run the commands followed by -//It will generate and a BinarySearch.class file which is a file containing java bytecode that is executed by JVM. +public class BinarySearch { + + static int binarySearch(int arr[], int key) + { + int start = 0; + int end = arr.length - 1; + + while (start <= end) { + // We use (start + (end - start)/2) rather than using (start + end)/2 to avoid + // arithmetic overflow. + // Arithmetic overflow is the situation when the value of a variable increases + // beyond the maximum value of the memory location, and wraps around. + int mid = start + (end - start) / 2; // optimised way + + if (arr[mid] == key)// key element is found at the middle of the array + return mid; + + else if (arr[mid] < key) {// so the key lies in the right hand side of array + start = mid + 1; + } + + else {// so the key lies in the left subarray + end = mid - 1; + } + } + // we reach here when the key element is not present + return -1; + } + + public static void main(String[] args) + { + + int arr[] = { 1, 3, 4, 5, 6 }; + + /* + * List> arr = new ArrayList<>(); + * arr.add(new ArrayList(Arrays.asList( 1, 3, 4, 5, 6 ))); + */ + int key = 4; // element to search + int index = binarySearch(arr, key); + if (index == -1) { + System.out.println("key element not found"); + } + else { + System.out.println("key element found at index :" + index); + } + + } +} From 1d1a3468e7af883fd4c9657cc4e8b8a02811285a Mon Sep 17 00:00:00 2001 From: Hridyansh Pareek Date: Thu, 18 Aug 2022 18:53:20 +0530 Subject: [PATCH 61/91] chore(Python) : add prime number check (#802) * Added Prime Number checker alorithm * Added Prime Number Checker Algorithm: * Update prime_number.py --- algorithms/Python/README.md | 4 ++++ .../Python/number_theory/prime_number.py | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+) create mode 100644 algorithms/Python/number_theory/prime_number.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index b2be029d..7cfd6fa9 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -83,3 +83,7 @@ ## Queues - [First in First out Queue](queues/fifo-queue.py) + + +##Number Theory +- [Prime Number Checker][number_theory/prime_number.py] \ No newline at end of file diff --git a/algorithms/Python/number_theory/prime_number.py b/algorithms/Python/number_theory/prime_number.py new file mode 100644 index 00000000..aca81cfe --- /dev/null +++ b/algorithms/Python/number_theory/prime_number.py @@ -0,0 +1,22 @@ +#TO CHECK WHETHER A NUMBER IS PRIME OR NOT + + +def isPrime(N): + if N<=1: + return False + + for i in range(2, int(N**0.5) + 1): + if N%i==0: + return False + + return True + +# TIME COMPLEXITY - O(sqrt(N)) + +# EXAMPLES +# print(isPrime(3)) -> True +# print(isPrime(15)) -> False + +# We are just checking till sqrt(N) as if their is any factor of a number +# greater than sqrt(N) then it's partner will be less than sqrt(N) as if a*b>N +# and a>=sqrt(N) then b<=sqrt(N) as if b>sqrt(N) then a*b>N. From 9a74c3e8571faf80d4231366d03bdde04a731701 Mon Sep 17 00:00:00 2001 From: Ming Tsai Date: Sat, 20 Aug 2022 11:48:10 -0400 Subject: [PATCH 62/91] chore(codespell): add ignore for the Turkish folder --- .github/workflows/codespell.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index 745b104f..3db88c38 100644 --- a/.github/workflows/codespell.yml +++ b/.github/workflows/codespell.yml @@ -11,4 +11,4 @@ jobs: - uses: actions/checkout@v2 - uses: actions/setup-python@v2 - run: pip install codespell - - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./docs/es,./.github,./algorithms/CSharp/test" + - run: codespell --ignore-words-list="ans,nnumber,nin,Hel" --quiet-level=2 --skip="**/**/package-lock.json,./docs/pt,./docs/es,./docs/tr,./.github,./algorithms/CSharp/test" From d34acc78b07146b42e43bc485fc6facc5218bf2b Mon Sep 17 00:00:00 2001 From: Ming Tsai Date: Sat, 20 Aug 2022 11:48:26 -0400 Subject: [PATCH 63/91] docs: fix typos --- algorithms/C/maths/fibonacci-number/README.md | 2 +- algorithms/CPlusPlus/Maths/factorial.cpp | 4 ++-- algorithms/CPlusPlus/Recursion/first-uppercase-letter.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/algorithms/C/maths/fibonacci-number/README.md b/algorithms/C/maths/fibonacci-number/README.md index 7d5101c1..2af27e9a 100644 --- a/algorithms/C/maths/fibonacci-number/README.md +++ b/algorithms/C/maths/fibonacci-number/README.md @@ -1,5 +1,5 @@ # Fibonacci Number -Fibonacci numbers form a Fibonacci sequence where given any number (excluding first 2 terms) is a sum of its two preceding numbers. Usually, the sequence is either start with 0 and 1 or 1 and 1. Below is a Fibonacci sequnce starting from 0 and 1: +Fibonacci numbers form a Fibonacci sequence where given any number (excluding first 2 terms) is a sum of its two preceding numbers. Usually, the sequence is either start with 0 and 1 or 1 and 1. Below is a Fibonacci sequence starting from 0 and 1: $$ 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, \dots diff --git a/algorithms/CPlusPlus/Maths/factorial.cpp b/algorithms/CPlusPlus/Maths/factorial.cpp index 11ad4773..a97f98c1 100644 --- a/algorithms/CPlusPlus/Maths/factorial.cpp +++ b/algorithms/CPlusPlus/Maths/factorial.cpp @@ -4,8 +4,8 @@ A factorial of number 4 is calculated as: 4 X 3 X 2 X 1 = 24 Approach: Calculating factorial using for loop. -Declaring the f varialbe to 1 (not initialising it to zero because any number multiplied by 0 will be 0) -Multiplying the f variable to 1,2,3...n and storing it in the f varialbe. +Declaring the f variable to 1 (not initialising it to zero because any number multiplied by 0 will be 0) +Multiplying the f variable to 1,2,3...n and storing it in the f variable. The same factorial can be calculated using while loop, recursion. Time Complexity: O(number) diff --git a/algorithms/CPlusPlus/Recursion/first-uppercase-letter.cpp b/algorithms/CPlusPlus/Recursion/first-uppercase-letter.cpp index 2be87827..40315a35 100644 --- a/algorithms/CPlusPlus/Recursion/first-uppercase-letter.cpp +++ b/algorithms/CPlusPlus/Recursion/first-uppercase-letter.cpp @@ -1,7 +1,7 @@ /* Description: Program to print the first uppercase letter in a string -Approach: Use a varialbe to iterate over the string +Approach: Use a variable to iterate over the string Increment the iterator by 1 at every recursive call If the value of iterator reaches till the length of the string, return '\0 From f4353ff2a46715825461ec11d64eaab7d6af6665 Mon Sep 17 00:00:00 2001 From: Mohnish Deshpande <77594965+mohnishdeshpande@users.noreply.github.com> Date: Sun, 21 Aug 2022 01:50:26 +1000 Subject: [PATCH 64/91] enh(CPlusPlus): update comment of binary search (#807) --- algorithms/CPlusPlus/Searching/binary-search.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/algorithms/CPlusPlus/Searching/binary-search.cpp b/algorithms/CPlusPlus/Searching/binary-search.cpp index 0603d02e..c07771de 100644 --- a/algorithms/CPlusPlus/Searching/binary-search.cpp +++ b/algorithms/CPlusPlus/Searching/binary-search.cpp @@ -7,7 +7,7 @@ int binarySearch(int arr[], int l, int r, int x) { if (r >= l) { int mid = l + (r - l) / 2; - //We use (l + (r - l)) rather than using (l - r) to avoid arithmetic overflow. + //We use (l + (r - l)) rather than using (l + r) to avoid arithmetic overflow. //Arithmetic overflow is the situation when the value of a variable increases //beyond the maximum value of the memory location, and wraps around. @@ -15,7 +15,7 @@ int binarySearch(int arr[], int l, int r, int x) if (arr[mid] == x) return mid; - // If element is smaller than mid, then it can only be present in left subarray + // If mid is greater than element, then it can only be present in left subarray if (arr[mid] > x) return binarySearch(arr, l, mid - 1, x); From 8649eda4b1547729fcf5219e036a63b5eff176dd Mon Sep 17 00:00:00 2001 From: Akashdeep Tickoo Date: Sat, 20 Aug 2022 21:24:06 +0530 Subject: [PATCH 65/91] docs(Python): add missing space on README (#809) --- algorithms/Python/README.md | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 7cfd6fa9..b7c82fd7 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -84,6 +84,5 @@ ## Queues - [First in First out Queue](queues/fifo-queue.py) - -##Number Theory -- [Prime Number Checker][number_theory/prime_number.py] \ No newline at end of file +## Number Theory +- [Prime Number Checker](number_theory/prime_number.py) From 005af5d471a878e35dc07ae227fa4782d9bc776f Mon Sep 17 00:00:00 2001 From: Sandra Date: Thu, 25 Aug 2022 11:54:32 +0530 Subject: [PATCH 66/91] add-new-file --- algorithms/CPlusPlus/Arrays/sparse_matrix.cpp | 40 +++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 algorithms/CPlusPlus/Arrays/sparse_matrix.cpp diff --git a/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp b/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp new file mode 100644 index 00000000..a7526beb --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp @@ -0,0 +1,40 @@ +/*Description :c++ solution to check if a given matrix is sparse matrix. +If the count of zeroes present in the mmatrix is more than half the elements of the matrix, +it is flagged as a sparse matrix.*/ + + +#include +using namespace std; +int main () { + int a[10][10] = { {0, 0, 9} , {5, 0, 8} , {7, 0, 0} }; + int i, j, count = 0; + int row = 3, col = 3; + for (i = 0; i < row; ++i) { + for (j = 0; j < col; ++j){ + if (a[i][j] == 0) + count++; + } + } + cout<<"The matrix is:"< ((row * col)/ 2)) + cout<<"This is a sparse matrix"< Date: Sat, 27 Aug 2022 16:45:55 +0000 Subject: [PATCH 67/91] docs(en): add doubly linked list (#813) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- docs/en/Lists/doubly-linked-list.md | 71 +++++++++++++++++++++++++++++ docs/en/README.md | 4 ++ 2 files changed, 75 insertions(+) create mode 100644 docs/en/Lists/doubly-linked-list.md diff --git a/docs/en/Lists/doubly-linked-list.md b/docs/en/Lists/doubly-linked-list.md new file mode 100644 index 00000000..1bb753cc --- /dev/null +++ b/docs/en/Lists/doubly-linked-list.md @@ -0,0 +1,71 @@ +# Doubly Linked List + +A doubly linked list is a type of linked data structure that allows traversal in both directions (forward and backward directions). +It differs from singly linked list in that, singly linked list does not support backward traversal. +Every node in a doubly linked list contains a **data** part and two pointers; **next pointer** that points to the next node and the **prev pointer** that points to the previous node in the list. +A doubly linked list also has two dummy nodes (head and tail) known as **sentinels** (guard nodes) that contains no data of the sequence. +The first element of a doubly linked list has its prev pointer pointing to head and the last element has its next node pointing to tail. + +Without a tail pointer, you cannot directly access the last element without having to first traverse the entire list all the way from the beginning. + +## Steps to create a doubly linked list +To create an empty list, +- create head and tail nodes (nodes without data) first +- let the **next pointer** of the head point to the tail node +- let the **prev pointer** of the tail point to the head node. + +For a non-empty list, +- let the next pointer of the head point to the first real element of the sequence +- let the prev pointer of the tail point to the last real element of the sequence + +## Key operations +- Insertion (insert at the beginning, at the end or anywhere in the middle) +- deletion (delete from beginning, end or anywhere in the middle) + +To add an element(node) at the beginning of the list, let the; +- *next pointer* of the new element (node) point to the first element (the one the *head* currently points to) +- *next pointer* of the *head* point to this new element you want to add +- *prev pointer* of the element (node) you want to add point to *head*. + +To add an alement (node) to the end of the list, let the; +- *prev pointer* of the new element you want to add point to the last element (the one before the *tail*) +- *next pointer* of the last element (the one before the *tail*) point to the new element you want to add +- *prev pointer* of the *tail* point to the new element. + +To delete an element from the beginning, let the; +- *next pointer* of the *head* point to the second element in the list (node after the one *head* pointers to). +- *prev pointer* of the second element point to the *head* + + +To delete from the end of the list, let the; +- *prev pointer* of the *tail* point to the element before the last node +- *next pointer* of the element before the last node point to the *tail* + +Note: If there is only one element in the list, deletion from both directions happens by pointing the *next pointer* of *head* to *tail* and *prev pointer* of *tail* to *head*. + +Deletion anywhere in the middle happens by letting the *prev pointer* and the *next pointer* of the node after and before the one you want to delete point to each other respectively. + +To insert anywhere in the middle, let the; +- *next pointer* of the element you want to insert point to the node at the position you want to insert it +- *prev pointer* of the element you want to insert point to node before the position you want to insert it +- *prev pointer* of the node at the position you want to insert point to the new element +- *next pointer* of the node before the position you want to insert point to the new element. + +Deletion and insertion at the beginning or end of the list is a constant operation and has a O(1) runtime. Deletion or insertion anywhere in the middle however has a O(n) runtime. + + +## Implementation + +- [C++](../../../algorithms/C/linked-lists/doubly-linked-list.c) +- [Java](../../../algorithms/CPlusPlus/Linked-Lists/doubly.cpp) +- [JavaScript](../../../algorithms/Java/linked-lists/doubly.java) +- [Python](../../../algorithms/Python/linked_lists/doubly.py) + +## Video URL + +[Doubly linked list](https://www.youtube.com/watch?v=nquQ_fYGGA4) + + +## References + +[Goodrich, T. M., Tamassia, R., Goldwasser, M.H.(2014). *Data Structures & Algorithms in Java* (6th ed.). Wiley](https://www.wiley.com/en-us/Data+Structures+and+Algorithms+in+Java,+6th+Edition-p-9781118771334) diff --git a/docs/en/README.md b/docs/en/README.md index 57254776..65b4a7cf 100644 --- a/docs/en/README.md +++ b/docs/en/README.md @@ -1,5 +1,9 @@ # Algorithms +## Lists +- [Singly linked list](./Lists/singly-linked-list.md) +- [Doubly linked list](./Lists/doubly-linked-list.md) + ## Sorting - [Bubble Sort](./Sorting/Bubble-Sort.md) From b0f8c38565cb8c15db78c409cb4a5993cc338da7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ana=20Karina=20Vergara=20Guzm=C3=A1n?= <37852043+anver-dev@users.noreply.github.com> Date: Sat, 27 Aug 2022 12:01:29 -0500 Subject: [PATCH 68/91] docs(Spanish): add merge sort (#819) --- docs/es/Ordenamiento/Merge-Sort.md | 35 ++++++++++++++++++++++++++++++ docs/es/README.md | 2 +- 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 docs/es/Ordenamiento/Merge-Sort.md diff --git a/docs/es/Ordenamiento/Merge-Sort.md b/docs/es/Ordenamiento/Merge-Sort.md new file mode 100644 index 00000000..808b7d6b --- /dev/null +++ b/docs/es/Ordenamiento/Merge-Sort.md @@ -0,0 +1,35 @@ +# Merge Sort + +Merge Sort es un algoritmo "Divide y venceras". Divide la matriz de entrada en dos mitades, se llama a sí mismo para cada una de ellas y luego fusiona las dos mitades ordenadas. + +## Pasos + +1. Encuentra el punto medio para dividir la matriz en dos mitades. +2. Llama a mergeSort para la primera mitad. +3. Llama a mergeSort para la segunda mitad. +4. Combina las dos mitades ordenadas en los pasos 2 y 3. + +## Ejemplo + +Dado el arreglo: +**12 11 13 5 6 7** + +El arreglo ordenado es +**5 6 7 11 12 13** + +## Implementación + +- [Java](../../../algorithms/Java/sorting/merge-sort.java) +- [C](../../../algorithms/C/sorting/merge-sort.c) +- [C++](../../../algorithms/CPlusPlus/Sorting/merge-sort.cpp) +- [JavaScript](../../../algorithms/JavaScript/src/sorting/merge-sort.js) +- [Python](../../../algorithms/Python/sorting/merge_sort.py) +- [C#](../../../algorithms/CSharp/src/Sorts/merge-sort.cs) + +## URL del video + +[Video de Youtube acerca de Merge Sort](https://www.youtube.com/watch?v=jlHkDBEumP0) + +## Otros + +[Wikipedia](https://en.wikipedia.org/wiki/Merge_sort) \ No newline at end of file diff --git a/docs/es/README.md b/docs/es/README.md index fcd7d5f8..cb97cd86 100644 --- a/docs/es/README.md +++ b/docs/es/README.md @@ -1,7 +1,7 @@ # Algoritmos ## Ordenamiento - +- [Merge Sort](./Ordenamiento/Merge-Sort.md) - [Quick Sort](./Ordenamiento/Quick-Sort.md) ## Otro From 7d0f490e7b0a69d3f3c140dacac51ea9004be47f Mon Sep 17 00:00:00 2001 From: Ayomide AJAYI <70599813+ayo-ajayi@users.noreply.github.com> Date: Sat, 27 Aug 2022 19:24:44 +0200 Subject: [PATCH 69/91] chore(Go): add selection sort (#820) --- algorithms/Go/README.md | 3 +- algorithms/Go/sorting/selection-sort.go | 62 +++++++++++++++++++++++++ 2 files changed, 64 insertions(+), 1 deletion(-) create mode 100644 algorithms/Go/sorting/selection-sort.go diff --git a/algorithms/Go/README.md b/algorithms/Go/README.md index 0e12c10e..febe548e 100644 --- a/algorithms/Go/README.md +++ b/algorithms/Go/README.md @@ -19,7 +19,8 @@ ## Sorting - [Bubble Sort](sorting/bubble-sort.go) - [Insertion Sort](sorting/insertion-sort.go) -- [Quicksort](sorting/quicksort.go) +- [Quick Sort](sorting/quicksort.go) +- [Selection Sort](sorting/selection-sort.go) ## Recursion - [Fibonacci](recursion/fibonacci.go) diff --git a/algorithms/Go/sorting/selection-sort.go b/algorithms/Go/sorting/selection-sort.go new file mode 100644 index 00000000..4975ce34 --- /dev/null +++ b/algorithms/Go/sorting/selection-sort.go @@ -0,0 +1,62 @@ +/* + Selection sort algorithm sorts an array by repeatedly finding the minimum element (considering ascending order) from unsorted part and putting it at the beginning. + The algorithm maintains two subarrays in a given array: + The subarray which is already sorted. + Remaining subarray which is unsorted. + Average Time Complexity: O(n^2) + + Link for reference: https://www.geeksforgeeks.org/selection-sort/ + +*/ + +package sorting + +import "fmt" + +func RunSelectionSortRec() { + arr := []int{7, 4, 7, 3, 2} + selSortRec(arr, len(arr)-1) //using recursion + fmt.Println(arr) // 2, 3, 4, 7, 7 +} +func RunSelectionSortIter() { + arr := []int{7, 4, 7, 3, 1} + selSort(arr) //using iteration + fmt.Println(arr) // 1, 3, 4, 7, 7 +} + +//sort using iterative method +func selSort(arr []int) { + for arrIndex := range arr { + minVal := arr[arrIndex] + minIndex := arrIndex + for subIndex := arrIndex + 1; subIndex < len(arr); subIndex++ { + if arr[subIndex] < minVal { + minVal = arr[subIndex] + minIndex = subIndex + } + } + arr[minIndex], arr[arrIndex] = arr[arrIndex], arr[minIndex] + } +} + +//sort using recursive method +func selSortRec(arr []int, i int) { + if i < 0 { + return + } + maxIn := maxSel(arr, i) + //i = len(arr)-1 + if i != maxIn { + arr[i], arr[maxIn] = arr[maxIn], arr[i] + } + selSortRec(arr, i-1) +} +func maxSel(arr []int, i int) int { + if i > 0 { + maxIn := maxSel(arr, i-1) + if arr[i] < arr[maxIn] { + return maxIn + } + } + return i +} From b5aaf761e3c62aa4f5282cc1a8fda281f857b86f Mon Sep 17 00:00:00 2001 From: Sandra Date: Sun, 28 Aug 2022 23:12:51 +0530 Subject: [PATCH 70/91] add tupple form --- algorithms/CPlusPlus/Arrays/sparse_matrix.cpp | 76 ++++++++++++++++--- 1 file changed, 66 insertions(+), 10 deletions(-) diff --git a/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp b/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp index a7526beb..786c5a76 100644 --- a/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp +++ b/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp @@ -1,40 +1,96 @@ /*Description :c++ solution to check if a given matrix is sparse matrix. If the count of zeroes present in the mmatrix is more than half the elements of the matrix, -it is flagged as a sparse matrix.*/ +it is flagged as a sparse matrix. +Also the tuple form of the matrix(if the said matrix is sparse) is displayed.*/ #include using namespace std; + +int compactMatrix(int sparseMatrix[4][5]) +{ + int size = 0; + for (int i = 0; i < 4; i++) + for (int j = 0; j < 5; j++) + if (sparseMatrix[i][j] != 0) + size++; + + /* number of columns in compactMatrix (size) must be + equal to number of non - zero elements in sparseMatrix */ + int compactMatrix[size][3]; + + // Making of new matrix + int k = 0; + for (int i = 0; i < 4; i++) + for (int j = 0; j < 5; j++) + if (sparseMatrix[i][j] != 0) + { + compactMatrix[k][0] = i; + compactMatrix[k][1] = j; + compactMatrix[k][2] = sparseMatrix[i][j]; + k++; + } + cout<<"The tuple form is:"< ((row * col)/ 2)) - cout<<"This is a sparse matrix"< Date: Sun, 28 Aug 2022 16:59:58 -0400 Subject: [PATCH 71/91] docs(reviewers): add go reviewer Add ayo-ajayi --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index ecb02edb..a9b61fc2 100644 --- a/README.md +++ b/README.md @@ -124,7 +124,7 @@ The programming should keep the naming convention rule of each programming langu | C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7, @Ashborn-SM | | Java | @TawfikYasser, @aayushjain7 | | C# | @ming-tsai, @Waqar-107 | -| Go | | +| Go | @ayo-ajayi | | Python | @Arsenic-ATG, @sridhar-5 | | JavaScript | @ming-tsai | From 710d7bfbf61d57ae84609f27a2964309b960f7e5 Mon Sep 17 00:00:00 2001 From: Prashant Bhapkar Date: Mon, 29 Aug 2022 20:39:31 +0530 Subject: [PATCH 72/91] Find Second largest element in the array --- algorithms/C/arrays/secondLargestElement.c | 30 ++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 algorithms/C/arrays/secondLargestElement.c diff --git a/algorithms/C/arrays/secondLargestElement.c b/algorithms/C/arrays/secondLargestElement.c new file mode 100644 index 00000000..04263d26 --- /dev/null +++ b/algorithms/C/arrays/secondLargestElement.c @@ -0,0 +1,30 @@ +//Second largest element in the array + +#include +#include + +int second(int arr[],int size) +{ + int max1=arr[0],max2; + for(int i=0;imax1) //Find largest element in the array + { + max2=max1; + max1=arr[i]; + } + else if (arr[i]>max2 && arr[i] Date: Wed, 31 Aug 2022 02:31:17 +0300 Subject: [PATCH 73/91] Open chore(CPlusPlus): add Floyd Warshall algorithm (#791) --- .../CPlusPlus/Graphs/floyd-warshall.cpp | 106 ++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 107 insertions(+) create mode 100644 algorithms/CPlusPlus/Graphs/floyd-warshall.cpp diff --git a/algorithms/CPlusPlus/Graphs/floyd-warshall.cpp b/algorithms/CPlusPlus/Graphs/floyd-warshall.cpp new file mode 100644 index 00000000..4f064f0b --- /dev/null +++ b/algorithms/CPlusPlus/Graphs/floyd-warshall.cpp @@ -0,0 +1,106 @@ +#include + +using namespace std; +const int N = 500, OO = 1e9; + +int dist[N][N]; + +//Initialize the distance matrix with infinities to indicate that there is no edge between nodes +void initialize_dist(int n) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + dist[i][j] = OO; + if (i == j) { + dist[i][j] = 0; + } + } + } +} + +//Take Edge input and update the distance matrix +void input(int m) { + for (int i = 0; i < m; i++) { + int a, b, c; + cin >> a >> b >> c; + dist[a][b] = c; + dist[b][a] = c; + } +} + +//Perform Floyd-Warshall algorithm to calculate all shortest paths +int floyd(int n) { + for (int k = 0; k < n; k++) { + for (int i = 0; i < n; i++) { + for (int j = 0; j < n; j++) { + if (dist[i][j] > dist[i][k] + dist[k][j]) { + dist[i][j] = dist[i][k] + dist[k][j]; + } + } + } + } +} + +//Take queries and output the shortest distance for each query +void output(int q) { + for (int i = 0; i < q; i++) { + int x, y; + cin >> x >> y; + cout << dist[x][y] << endl; + } +} + +int main() { + int n, m, q; + cin >> n; // Number of nodes + initialize_dist(n); + cin >> m; // Number of edges + input(m); + floyd(n); + cin >> q; // Number of queries + output(q); + return 0; +} + +/* +Time Complexity: O(n^3) +Memory Complexity: O(n^2) +*/ + +/* +Example: + 5 // Number of nodes + 10 // Number of edges + 0 1 5 // Edge from Node 0 to Node 1 with Weight 5 + 0 2 3 + 0 3 4 + 0 4 1 + 1 2 4 + 1 3 1 + 1 4 1 + 2 3 1 + 2 4 2 + 3 4 4 + 10 // Number of Queries + 0 1 // Print Minimum Path between Nodes 0 and 1 + 0 2 + 0 3 + 0 4 + 1 2 + 1 3 + 1 4 + 2 3 + 2 4 + 3 4 + +Output: + 2 //Minimum path from 0 to 1 + 3 //Minimum path from 0 to 2 + 3 //Minimum path from 0 to 3 + 1 //Minimum path from 0 to 4 + 2 //Minimum path from 1 to 2 + 1 //Minimum path from 1 to 3 + 1 //Minimum path from 1 to 4 + 1 //Minimum path from 2 to 3 + 2 //Minimum path from 2 to 4 + 2 //Minimum path from 3 to 4 + */ diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 0350073e..1dd328c6 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -51,6 +51,7 @@ - [Connected Components](Graphs/total-connected-components.cpp) - [Dijkstra's Algorithm](Graphs/dijkstra.cpp) - [Cycle Detection](Graphs/cycle-detection.cpp) +- [Floyd Warshall](Graphs/floyd-warshall.cpp) ## Multiplication From 4a7eba4d2bad217c8f76ceb25c04efd2daeadf27 Mon Sep 17 00:00:00 2001 From: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> Date: Tue, 30 Aug 2022 19:38:25 -0400 Subject: [PATCH 74/91] docs(readme): add C/C++ reviewer --- README.md | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index a9b61fc2..239d8e04 100644 --- a/README.md +++ b/README.md @@ -119,14 +119,14 @@ The programming should keep the naming convention rule of each programming langu ## Reviewers -| Programming Language | Users | -| -------------------- | ------------------------------------------------ | -| C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7, @Ashborn-SM | -| Java | @TawfikYasser, @aayushjain7 | -| C# | @ming-tsai, @Waqar-107 | -| Go | @ayo-ajayi | -| Python | @Arsenic-ATG, @sridhar-5 | -| JavaScript | @ming-tsai | +| Programming Language | Users | +| -------------------- | ----------------------------------------------------------- | +| C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7, @Ashborn-SM, @Ashad001 | +| Java | @TawfikYasser, @aayushjain7 | +| C# | @ming-tsai, @Waqar-107 | +| Go | @ayo-ajayi | +| Python | @Arsenic-ATG, @sridhar-5 | +| JavaScript | @ming-tsai | ## Contributors From 41ace4231f75646983f53a086b107a54f689246e Mon Sep 17 00:00:00 2001 From: Prashant Bhapkar Date: Wed, 31 Aug 2022 16:30:53 +0530 Subject: [PATCH 75/91] Added running time of algorithm and update readme.md file --- algorithms/C/README.md | 1 + algorithms/C/arrays/secondLargestElement.c | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 9e241b51..50a7eb55 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -7,6 +7,7 @@ - [Reverse an array](arrays/reverse-array.c) - [Maximum difference](arrays/maximum-difference.c) - [Largest Element](arrays/largestElement.c) +- [Second Largest Element](arrays/secondLargestElement.c) - [Sieve of Eratosthenes](arrays/sieve-of-eratosthenes.c) ## Bit Manipulation diff --git a/algorithms/C/arrays/secondLargestElement.c b/algorithms/C/arrays/secondLargestElement.c index 04263d26..34b81d12 100644 --- a/algorithms/C/arrays/secondLargestElement.c +++ b/algorithms/C/arrays/secondLargestElement.c @@ -28,3 +28,11 @@ int main() second(arr,size); return 0; } + +/* +----------------Sample Output---------------- +> 88 45 + +Time Compexity: O(n) +Space compexity: O(1) +*/ From 3a657980245f49c5ee4ff68a094882f2ab0dfb67 Mon Sep 17 00:00:00 2001 From: Sandra Date: Thu, 1 Sep 2022 16:40:53 +0530 Subject: [PATCH 76/91] updated readme --- algorithms/CPlusPlus/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/algorithms/CPlusPlus/README.md b/algorithms/CPlusPlus/README.md index 0350073e..40c98abb 100644 --- a/algorithms/CPlusPlus/README.md +++ b/algorithms/CPlusPlus/README.md @@ -30,6 +30,8 @@ - [All unique triplet that sum up to given value](Arrays/three-sum.cpp) - [Next permutation](Arrays/next-permutation.cpp) - [Maximum Minimum Average of numbers](Arrays/max-min-avg.cpp) +- [Sparse Matrix](Arrays/sparse_matrix.cpp) + ## Dynamic-Programming From 28ff13a2a4ebdd8c04165c328b7ef310be94dc29 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ana=20Karina=20Vergara=20Guzm=C3=A1n?= <37852043+anver-dev@users.noreply.github.com> Date: Thu, 1 Sep 2022 10:38:36 -0500 Subject: [PATCH 77/91] docs(Spanish): add bubble sort (#825) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- docs/es/Ordenamiento/Bubble-Sort.md | 60 +++++++++++++++++++++++++++++ docs/es/README.md | 5 ++- 2 files changed, 63 insertions(+), 2 deletions(-) create mode 100644 docs/es/Ordenamiento/Bubble-Sort.md diff --git a/docs/es/Ordenamiento/Bubble-Sort.md b/docs/es/Ordenamiento/Bubble-Sort.md new file mode 100644 index 00000000..4fe94d70 --- /dev/null +++ b/docs/es/Ordenamiento/Bubble-Sort.md @@ -0,0 +1,60 @@ +# Ordenamiento de Burbuja + +Bubble Sort, también conocido como Sinking Sort, es el algoritmo de clasificación más simple. Intercambia los números si no están en el orden correcto. La complejidad del tiempo en el peor de los casos es O(n^2) + +## Pasos + +1. Compara el primer elemento con el siguiente elemento. +2. Si el primer elemento es más grande que el siguiente, los elementos se intercambian. +3. Se realiza el paso 2 hasta que el número seleccionado se coloca en su posición correcta y luego se compara el siguiente elemento. +4. Se realizan varias pasadas hasta que se completa la clasificación. + +## Ejemplo + +Dado el arreglo: +**5 1 4 2 8** + +La arreglo ordenado es +**1 2 4 5 8** + +Pasos +**Primer vuelta** + +- ( **5 1** 4 2 8 ) → ( **1 5** 4 2 8 ), Aquí, el algoritmo compara los dos primeros elementos y los intercambia desde 5 > 1. +- ( 1 **5 4** 2 8 ) → ( 1 **4 5** 2 8 ), Intercambia desde 5 > 4 +- ( 1 4 **5 2** 8 ) → ( 1 4 **2 5** 8 ), Intercambia desde 5 > 2 +- ( 1 4 2 **5 8** ) → ( 1 4 2 **5 8** ), Ahora, dado que estos elementos ya están en orden (8 > 5), el algoritmo no los intercambia. + +**Segunda vuelta** + +- ( **1 4** 2 5 8 ) → ( **1 4** 2 5 8 ) +- ( 1 **4 2** 5 8 ) → ( 1 **2 4** 5 8 ), Intercambia desde 4 > 2 +- ( 1 2 **4 5** 8 ) → ( 1 2 **4 5** 8 ) +- ( 1 2 4 **5 8** ) → ( 1 2 4 **5 8** ) + +Ahora, el arreglo ya está ordenado, pero el algoritmo no sabe si está completo. El algoritmo necesita una vuelta completa adicional sin ningún intercambio para saber que está ordenado. + +**Tercera vuelta** + +- ( **1 2** 4 5 8 ) → ( **1 2** 4 5 8 ) +- ( 1 **2 4** 5 8 ) → ( 1 **2 4** 5 8 ) +- ( 1 2 **4 5** 8 ) → ( 1 2 **4 5** 8 ) +- ( 1 2 4 **5 8** ) → ( 1 2 4 **5 8** ) + +## Implementación + +- [C](../../../algorithms/C/sorting/bubble-sort.c) +- [C++](../../../algorithms/CPlusPlus/Sorting/bubble-sort.cpp) +- [CSharp](../../../algorithms/CSharp/src/Sorts/bubble-sort.cs) +- [Go](../../../algorithms/Go/sorting/bubble-sort.go) +- [Java](../../../algorithms/Java/sorting/bubble-sort.java) +- [JavaScript](../../../algorithms/JavaScript/src/sorting/bubble-sort.js) +- [Python](../../../algorithms/Python/sorting/bubble_sort.py) + +## URL del video + +[Video de Youtube acerca de Bubble Sort](https://www.youtube.com/watch?v=vnnL17I7pIY) + +## Otros + +[Wikipedia](https://es.wikipedia.org/wiki/Ordenamiento_de_burbuja) diff --git a/docs/es/README.md b/docs/es/README.md index cb97cd86..b144a2c8 100644 --- a/docs/es/README.md +++ b/docs/es/README.md @@ -1,8 +1,9 @@ # Algoritmos ## Ordenamiento -- [Merge Sort](./Ordenamiento/Merge-Sort.md) -- [Quick Sort](./Ordenamiento/Quick-Sort.md) +- [Ordenamiento de burbuja](./Ordenamiento/Bubble-Sort.md) +- [Ordenar por fusión](./Ordenamiento/Merge-Sort.md) +- [Ordenación rápida](./Ordenamiento/Quick-Sort.md) ## Otro From a68c012fea6ddf8097124a612b4f2eed97d3ab17 Mon Sep 17 00:00:00 2001 From: angshudas <110800802+angshudas@users.noreply.github.com> Date: Thu, 1 Sep 2022 21:09:18 +0530 Subject: [PATCH 78/91] chore(CPlusPlus): add prim's graph algorithm (#816) Co-authored-by: angshudas Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- .../CPlusPlus/Graphs/prim's_algorithm.cpp | 96 +++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 97 insertions(+) create mode 100644 algorithms/CPlusPlus/Graphs/prim's_algorithm.cpp diff --git a/algorithms/CPlusPlus/Graphs/prim's_algorithm.cpp b/algorithms/CPlusPlus/Graphs/prim's_algorithm.cpp new file mode 100644 index 00000000..613ac71d --- /dev/null +++ b/algorithms/CPlusPlus/Graphs/prim's_algorithm.cpp @@ -0,0 +1,96 @@ +/* + PREREQUISITE --> + 1. GRAPH + 2. PRIORITY QUEUE +*/ + +#include +using namespace std; + +vector>> graph; +vector vis; + +int primAlgorithm(){ + int totalCost = 0; + // totalCost will store the minimum spanning tree + set> pq; + /* + here pq -> priority queue ( it sorts all elements ) + it takes two value + 1. weight + 2. vertex + + Here, priority queue will be sorted according to weight + */ + + + pq.insert({0,1}); + /* + initialising the priority queue with {0,1} + Since, vertex 1 is the first vertex so we don't have to travel through a + edge to reach vertex 1 + */ + + while( !pq.empty() ){ + // taking the values of first elements from priority queue + int wt = (*pq.begin()).first; // weight of first vertex in priority queue + int v = (*pq.begin()).second; // first vertex + pq.erase(pq.begin()); + + if( vis[v] ) continue; + // if the vertex 'v' is visited then continue and don't proceed + vis[v] = true; + totalCost += wt; + // if the vertex is not visited then mark it visited + // and add the weight to total cost + + + // traverse all the child of vertex 'v' + for( auto elem : graph[v] ){ + + if( vis[elem.first] ) continue; + + // if child is visited then don't insert in priority queue + // else insert in priority queue + pq.insert({elem.second,elem.first}); + } + } + + graph.clear(); // clearing all values in graph + return totalCost; +} + +int main() +{ + int n,e; cin>>n>>e; + // n -> number of vertex in graph + // e -> number of edges in graph + + // initialising the graph + graph = vector>> (n+1); + + // initialising the visited vector to false + // it represent if the vertex is visited or not + vis = vector(n+1,false); + + + // taking the input of 'e' edges + for(int i=0; i>a>>b>>wt; + /* + a,b -> vertexs of graph + wt -> weight of edge between vertex 'a' and 'b' + */ + + graph[a].push_back({b,wt}); + graph[b].push_back({a,wt}); + // it creates adjcency list by pushing all + // the vertexs(with weight) which are directly connected by edges. + + } + + cout< Date: Fri, 2 Sep 2022 01:40:21 +1000 Subject: [PATCH 79/91] chore(CPlusPlus): add binary power on maths algorithm (#810) Co-authored-by: angshudas Co-authored-by: Mohnish Deshpande --- algorithms/CPlusPlus/Maths/binary-power.cpp | 56 +++++++++++++++++++++ algorithms/CPlusPlus/README.md | 1 + 2 files changed, 57 insertions(+) create mode 100644 algorithms/CPlusPlus/Maths/binary-power.cpp diff --git a/algorithms/CPlusPlus/Maths/binary-power.cpp b/algorithms/CPlusPlus/Maths/binary-power.cpp new file mode 100644 index 00000000..4362dfa0 --- /dev/null +++ b/algorithms/CPlusPlus/Maths/binary-power.cpp @@ -0,0 +1,56 @@ +#include +using namespace std; + +/* +The idea is to half the power on every iteration +Computes the power in log(n) operations + +On every iteration: +Square the base, half the power + +Special case - if power is odd: +Multiply the ans with a +Because the ODD-NUMBER % 2 == 1 + +Note: There will always be one iteration where power is odd +*/ + +long binpow(long a, long b){ + long ans=1; + // while b is greater than zero, we continue the binary exponentiation + while(b>0){ + // if b is odd, multiply result with base + if(b&1) + ans *= a; + // square the base + a *= a; + // half the power + b /= 2; + } + return ans; +} + +// source: @angshudas +long binpow_rec(long a, long b){ + // a^0 = 1 [for any a] + if(b==0) + return 1; + // recursive call for a^(b/2) + long ans = binpow_rec(a, b/2); + // square the result + ans *= ans; + // if b is odd, times by a + // to cover for + if(b&1) + ans *= a; + + return ans; +} + +int main(){ + long base, power; + cout<<"Enter the base and power: "<>base>>power; + cout< Date: Sun, 4 Sep 2022 15:08:24 +0530 Subject: [PATCH 81/91] chore(Java): add isomorphic strings (#828) * chore(Java): added isomorphic strings * added Time and space complexity * update algorithms/Java/README.md * update algorithms/Java/README.md file * spelling Correct README.md file --- algorithms/Java/README.md | 1 + .../Java/strings/isomorphic_strings.java | 61 +++++++++++++++++++ 2 files changed, 62 insertions(+) create mode 100644 algorithms/Java/strings/isomorphic_strings.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 70c32fad..09ffeb53 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -88,6 +88,7 @@ - [Boyer Moore Search](strings/Boyer_Moore.java) - [Reverse String](strings/reverse-string.java) - [First Non Repeating Character](strings/first-non-repeating-char.java) +- [Isomorphic Strings](strings/isomorphic_strings.java) ## Trees diff --git a/algorithms/Java/strings/isomorphic_strings.java b/algorithms/Java/strings/isomorphic_strings.java new file mode 100644 index 00000000..5079c21c --- /dev/null +++ b/algorithms/Java/strings/isomorphic_strings.java @@ -0,0 +1,61 @@ +/** + problem statement: + Given two strings- str1 and str2, check both are isomorphic or not + Isomorphic strings: Two strings are called isomorphic, + if there is a one to one mapping possible for every character of str1 to every character of str2 while preserving the order. + */ + + /*** + Example 1 => Input: str1="aab", str2="xxy" + Output: 1 + Example 2 => Input: str1="aab", str2="xyz" + Output: 0 + */ +/** + * + * Time Complexity: O(N) + Space Complexity: O(1) +*/ + + import java.util.Arrays; +import java.util.Scanner; + public class isomorphic_strings{ + public static void main(String[] args){ + Scanner input=new Scanner(System.in); + String str1=input.next(); + String str2=input.next(); + if(strings_are_isomorphic(str1,str2)){ + System.out.println("1"); + }else{ + System.out.println("0"); + } + } + public static boolean strings_are_isomorphic(String s1,String s2){ + int n=s1.length(); + int m=s2.length(); + //check length of both strings + if(n!=m){ + return false; + } + // array, make for mark visited characters of s2. + boolean visited[]=new boolean[256]; + //array, store mapping of every character from s1 to s2 + int map[]=new int[256]; + Arrays.fill(map,-1); + for (int i=0;i Date: Mon, 5 Sep 2022 06:25:17 +0530 Subject: [PATCH 82/91] chore(Java): add square root using binary search (#826) --- algorithms/Java/Maths/square-root.java | 49 ++++++++++++++++++++++++++ algorithms/Java/README.md | 1 + 2 files changed, 50 insertions(+) create mode 100644 algorithms/Java/Maths/square-root.java diff --git a/algorithms/Java/Maths/square-root.java b/algorithms/Java/Maths/square-root.java new file mode 100644 index 00000000..2c229a4e --- /dev/null +++ b/algorithms/Java/Maths/square-root.java @@ -0,0 +1,49 @@ +// Calculating Square root of a number which is not necessarily perfect square +// using Binary Search i.e. is using decrease and conquer approach +// Time: O(log(n)) +public class BinarySearchSQRT { + public static void main(String[] args) { + int n = 40; // number whose square root is to be calculated + int p = 3; // decimal precision required + + System.out.printf("%.3f", sqrt(n, p)); + } + static double sqrt(int n, int p) { + int s = 0; + int e = n; + + double root = 0.0; + + while (s <= e) { + int m = s + (e - s) / 2; //this method of calculating middle element avoids integer overflow + + if (m * m == n) { //the middle element is the required sqrt + return m; + } + else if (m * m > n) { //sqrt lies on the left part + e = m - 1; + } + else { // sqrt lies in the right part + s = m + 1; + root = m; + } + } + //now the root contains the nearest integer to the required square root + //now we need to add decimal precision to the root so that we can get as close to the exact sqrt + double incr = 0.1; //initialise + for (int i = 0; i < p; i++) { + while (root * root <= n) { //if the square of the root we have is less than the number + root += incr; //we will add incr decimal point each time + } + root -= incr; + incr /= 10; //here we increase the decimal point + } + + return root; //here we have root up to p decimal point + } +} + +/* +Output - +6.324 +*/ diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 09ffeb53..07a3d1c8 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -33,6 +33,7 @@ - [Catalan Numbers](Maths/catalan-numbers.java) - [Nth Geek Onacci Number](Maths/nth-geek-onacci-number.java) - [Random Node in Linked List](Maths/algorithms_random_node.java) +- [Square Root using BinarySearch](Maths/square-root.java) ## Queues From 033fbe1503c0b55f32a7f1584c9aba6b94ab98c8 Mon Sep 17 00:00:00 2001 From: Ivan Kirspu <69795291+luneyune@users.noreply.github.com> Date: Tue, 6 Sep 2022 20:31:56 +0700 Subject: [PATCH 83/91] chore(C): add bogo sort algorithm (#829) * Add bogo sort algorithm * Add bogo sort to README.md * Fix typo Co-authored-by: Ivan Kirspu --- algorithms/C/README.md | 1 + algorithms/C/sorting/bogo-sort.c | 83 ++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) create mode 100644 algorithms/C/sorting/bogo-sort.c diff --git a/algorithms/C/README.md b/algorithms/C/README.md index 95c7796c..f2391b1a 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -59,6 +59,7 @@ - [Quick Sort](sorting/quick-sort.c) - [Shell Sort](sorting/shell-sort.c) - [Radix Sort](sorting/radix-sort.c) +- [Bogo Sort](sorting/bogo-sort.c) ## Strings diff --git a/algorithms/C/sorting/bogo-sort.c b/algorithms/C/sorting/bogo-sort.c new file mode 100644 index 00000000..cb56f60e --- /dev/null +++ b/algorithms/C/sorting/bogo-sort.c @@ -0,0 +1,83 @@ +/* +[ALGORITHM]: Bogo sort - one of the most inefficient sorting algorithm + +[PROBLEM]: Given an array, of size n, sort it. + +[TIME COMPLEXITY]: O(N * N!) + +[SAMPLE OF OUTPUT]: + +Before sorting: +8 3 7 4 6 2 1 9 5 10 +After sorting: +1 2 3 4 5 6 7 8 9 10 +*/ + +#include +#include +#include +#include + +void swap(int *a, int *b) // Swap values between *a and *b +{ + int tmp = *a; + *a = *b; + *b = tmp; +} + +void shuffle(int *array, int size) // Randomly shuffles given array for further info check DSA/algorithms/C/arrays/shuffle_array.c +{ + for (int i = 0; i < size; i++) { + swap(array + i, array + (rand() % size)); + } +} + +bool is_sorted(int *array, int size) // If array is sorted (by non-reduction) return true, else false +{ + for (int i = 1; i < size; i++) { + if (array[i] < array[i - 1]) + return false; + } + return true; +} + +void bogo_sort(int *array, int size) // Until array is sorted randomly shuffles an array. +{ + while (!is_sorted(array, size)) + shuffle(array, size); +} + +void print_array(int *array, int size) // Printing array +{ + for (int i = 0; i < size; i++) { + printf("%d ", array[i]); + } + putchar('\n'); +} + +int main() +{ + srand(time(NULL)); // Setup of random seed for random generation + int array[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; + /* + Be accurate with size of array, sorting an array with 15 (for example) elements could + take unexpected amount of time. + + For example: + Sorting 15 elements is 36036 times longer than sorting 10 elements. + So, if sorting 10 elements take half a second, + then sorting 15 elements approximately take 5 hours (in real could longer). + */ + + shuffle(array, 10); // Shuffling an array before sorting + + printf("Before sorting:\n"); + print_array(array, 10); + + bogo_sort(array, 10); + printf("After sorting:\n"); + print_array(array, 10); + + return 0; +} + From e1bbc8b3020e607cd13c8fc5f2194c95a3c5995e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Andr=C3=A9s=20Mart=C3=ADnez?= <44838230+amartinez1224@users.noreply.github.com> Date: Tue, 6 Sep 2022 14:15:28 -0400 Subject: [PATCH 84/91] chore(Python): add find all permutations (#831) * added find_all_permutations * added test case for find_all_permutations * updated README with find all permutations * Added desc and time complexity of find_all_permutations * PR comment spelling correction --- algorithms/Python/README.md | 1 + .../Python/strings/find_all_permutations.py | 28 +++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 algorithms/Python/strings/find_all_permutations.py diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index b7c82fd7..9bcc929b 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -63,6 +63,7 @@ - [Unique Character](strings/unique_character.py) - [Add String](strings/add_string.py) - [Rabin Karp algorithm](strings/rabin-karp-algorithm.py) +- [Find all permutations](strings/find_all_permutations.py) ## Dynamic Programming - [Print Fibonacci Series Up To N-th Term](dynamic_programming/fibonacci_series.py) diff --git a/algorithms/Python/strings/find_all_permutations.py b/algorithms/Python/strings/find_all_permutations.py new file mode 100644 index 00000000..cffb75d7 --- /dev/null +++ b/algorithms/Python/strings/find_all_permutations.py @@ -0,0 +1,28 @@ +""" +Find all the permutations of a given string +Sample input: 'ABC' +Expected output: ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] +Description: The algorithm is recursive. In each recursion, each element of the string (left) is removed and added to the beginning (head). This process is repeated until left is empty. +Time complexity: (n!) +""" + +def permutation(head, left, permutations): + if len(left) == 0: + permutations.append(head) + else: + for i in range(len(left)): + permutation(head+left[i], left[:i]+left[i+1:], permutations) + +def find_all_permutations(string): + permutations = [] + permutation('', string, permutations) + return permutations + +if __name__ == "__main__": + input = 'ABC' + output = find_all_permutations(input) + + expected = ['ABC', 'ACB', 'BAC', 'BCA', 'CAB', 'CBA'] + assert len(output) == len(expected), f"Expected 6 permutations, got: {len(expected)}" + for perm in expected: + assert perm in output, f"Expected permutation {perm} to be in output, missing" From a5ae1dc09165600857b3d5ca32aa402a63aa01c1 Mon Sep 17 00:00:00 2001 From: Ishantgarg-web <57170623+Ishantgarg-web@users.noreply.github.com> Date: Sun, 11 Sep 2022 19:02:36 +0530 Subject: [PATCH 85/91] chore(Java): add next greater element (#833) * chore(Java): added Next Greater Element * Update Next_Greater_Element.java file --- algorithms/Java/README.md | 1 + .../Java/stacks/Next_Greater_Element.java | 79 +++++++++++++++++++ 2 files changed, 80 insertions(+) create mode 100644 algorithms/Java/stacks/Next_Greater_Element.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 07a3d1c8..1f658016 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -75,6 +75,7 @@ - [Celebrity Problem](stacks/celebrity-problem.java) - [Sliding Window Maximum](stacks/sliding-window-maximum.java) - [Min Stack](stacks/Min-Stack.java) +- [Next Greater Element](stacks/Next_Greater_Element.java) ## Strings diff --git a/algorithms/Java/stacks/Next_Greater_Element.java b/algorithms/Java/stacks/Next_Greater_Element.java new file mode 100644 index 00000000..887025f9 --- /dev/null +++ b/algorithms/Java/stacks/Next_Greater_Element.java @@ -0,0 +1,79 @@ +/*** + * Problem Statement: + * Given an array arr[] of size N having distinct elements, the task is to find the next greater element for each element of the array in order of their appearance in the array. + * Next greater element means nearest element on right side which is greater than current element, + * if there is no suxh element, then put -1 for that. + * + */ + + + /*** + * Example 1: Input: arr=[1,3,2,4] n=4 + Output: 3 4 4 -1 + + Example 2: Input: arr=[6 8 0 1 3] n=5 + Output: 8 -1 1 3 -1 + */ + + /*** + * Time Complexity: O(N) + * Space Complexity: O(N) + */ + import java.util.Scanner; +import java.util.Stack; + + public class Next_Greater_Element { + public static void main(String[] args){ + Scanner input=new Scanner(System.in); + int n=input.nextInt(); + long arr[]=new long[n]; + for (int i=0;i st=new Stack<>(); + st.push(arr[n-1]); + for (int i=n-2;i>=0;i--) + { + if(st.isEmpty()) + { + st.push(arr[i]); + ans[i]=-1; + } + else + { + while(st.isEmpty()==false && arr[i]>=st.peek()) + { + st.pop(); + } + if(st.size()==0){ + ans[i]=-1; + }else{ + ans[i]=st.peek(); + } + st.push(arr[i]); + } + } + return ans; + } + } + \ No newline at end of file From 7db2f01de77bb19641983b39f2c14c538f5c53dd Mon Sep 17 00:00:00 2001 From: Mohit Chakraverty <79406819+mohitchakraverty@users.noreply.github.com> Date: Mon, 12 Sep 2022 01:12:18 +0530 Subject: [PATCH 86/91] docs(readme): add Java reviewer (#836) Added myself in the reviewer's list --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 239d8e04..3a653dde 100644 --- a/README.md +++ b/README.md @@ -122,7 +122,7 @@ The programming should keep the naming convention rule of each programming langu | Programming Language | Users | | -------------------- | ----------------------------------------------------------- | | C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7, @Ashborn-SM, @Ashad001 | -| Java | @TawfikYasser, @aayushjain7 | +| Java | @TawfikYasser, @aayushjain7, @mohitchakraverty | | C# | @ming-tsai, @Waqar-107 | | Go | @ayo-ajayi | | Python | @Arsenic-ATG, @sridhar-5 | From 7f85abfa3176ec3dcffad0fb295ab2129c3056b0 Mon Sep 17 00:00:00 2001 From: Ishantgarg-web <57170623+Ishantgarg-web@users.noreply.github.com> Date: Mon, 12 Sep 2022 01:15:00 +0530 Subject: [PATCH 87/91] chore(Go): add anagram (#834) --- algorithms/Go/README.md | 1 + algorithms/Go/strings/anagram.go | 55 ++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 algorithms/Go/strings/anagram.go diff --git a/algorithms/Go/README.md b/algorithms/Go/README.md index febe548e..680a3d30 100644 --- a/algorithms/Go/README.md +++ b/algorithms/Go/README.md @@ -27,4 +27,5 @@ ## String - [Palindrome Permutation](strings/palindrome-permutation.go) +- [Anagram](strings/anagram.go) diff --git a/algorithms/Go/strings/anagram.go b/algorithms/Go/strings/anagram.go new file mode 100644 index 00000000..6ae30240 --- /dev/null +++ b/algorithms/Go/strings/anagram.go @@ -0,0 +1,55 @@ +package main + +/** +Problem Statement: Given two strings s and t, find they are anagrams or not +An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. + +**/ + +/*** +Example 1: Input: s="anagram" t="nagaram" + Output: true + +Example 2: Input: s="rat" t="car" + Output: false + +***/ + +/*** +Time complexity: O(n), n=length of string s +Space complexity: O(1) + +**/ + +import "fmt" + +func main() { + fmt.Println("Enter first string") + var first string + fmt.Scanln(&first) + fmt.Println("Enter second string") + var second string + fmt.Scanln(&second) + ans := isAnagram(first, second) + if ans == true { + fmt.Println("They are anagrams") + } else { + fmt.Println("They are not anagrams") + } +} +func isAnagram(s string, t string) bool { + var count [256]int + //var i int + for i := 0; i < len(s); i++ { + count[s[i]]++ + } + for i := 0; i < len(t); i++ { + count[t[i]]-- + } + for i := 0; i < len(count); i++ { + if count[i] != 0 { + return false + } + } + return true +} From daa8be12a492bf152fb903da76419e302f1e08da Mon Sep 17 00:00:00 2001 From: Ayomide AJAYI <70599813+ayo-ajayi@users.noreply.github.com> Date: Mon, 12 Sep 2022 02:44:32 +0200 Subject: [PATCH 88/91] enh(Go): import the string package on anagram (#838) --- algorithms/Go/strings/anagram.go | 15 +++++---------- algorithms/Go/strings/palindrome-permutation.go | 14 ++++++++------ 2 files changed, 13 insertions(+), 16 deletions(-) diff --git a/algorithms/Go/strings/anagram.go b/algorithms/Go/strings/anagram.go index 6ae30240..ca290e8d 100644 --- a/algorithms/Go/strings/anagram.go +++ b/algorithms/Go/strings/anagram.go @@ -1,29 +1,23 @@ -package main - /** Problem Statement: Given two strings s and t, find they are anagrams or not An Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once. -**/ - -/*** Example 1: Input: s="anagram" t="nagaram" Output: true Example 2: Input: s="rat" t="car" Output: false -***/ - -/*** Time complexity: O(n), n=length of string s Space complexity: O(1) **/ +package strings + import "fmt" -func main() { +func RunIsAnagram() { fmt.Println("Enter first string") var first string fmt.Scanln(&first) @@ -37,9 +31,10 @@ func main() { fmt.Println("They are not anagrams") } } + func isAnagram(s string, t string) bool { var count [256]int - //var i int + for i := 0; i < len(s); i++ { count[s[i]]++ } diff --git a/algorithms/Go/strings/palindrome-permutation.go b/algorithms/Go/strings/palindrome-permutation.go index 779f8660..62b158a9 100644 --- a/algorithms/Go/strings/palindrome-permutation.go +++ b/algorithms/Go/strings/palindrome-permutation.go @@ -1,3 +1,10 @@ +/* +Given a string s, return true if we can have a palindrome from the permutation of the input +A palindrome is a word, number, phrase, or other sequence of characters which reads the same backward as forward, such as madam or racecar. + + Time: O(n) + Space: O(n) +*/ package strings import( @@ -5,12 +12,7 @@ import( "fmt" ) -/* -Given a string s, return true if we can have a palindrome from the permutation of the input - Time: O(n) - Space: O(n) -*/ func canPermutePalindrome(s string) bool { a := strings.Split(s,"") dictionary := make(map[string] int) @@ -29,7 +31,7 @@ func canPermutePalindrome(s string) bool { //You are welcome to play around with the test cases -func runPermutationCheck(){ +func RunPermutationCheck(){ input1 := "carerac" fmt.Printf("%t for input %s \n", canPermutePalindrome(input1), input1) //should print true From eb3d410c092d40ca0cee18e0039f57751821bc9b Mon Sep 17 00:00:00 2001 From: Hemant Sharma <101392754+hemant097@users.noreply.github.com> Date: Thu, 15 Sep 2022 02:14:31 +0530 Subject: [PATCH 89/91] chore(Java): add left leaf sum binary tree (#839) --- algorithms/Java/README.md | 1 + algorithms/Java/trees/Left-Leaf-Sum.java | 95 ++++++++++++++++++++++++ 2 files changed, 96 insertions(+) create mode 100644 algorithms/Java/trees/Left-Leaf-Sum.java diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index 1f658016..ce60dd93 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -101,6 +101,7 @@ - [Min Heap](trees/MinHeap.java) - [Check Tree Traversal](trees/check-tree-traversal.java) - [Random Node of a binary tree](tree-random-node.java) +- [Left Leaf Sum of a Binary tree](trees/Left-Leaf-Sum.java) ## Backtracking diff --git a/algorithms/Java/trees/Left-Leaf-Sum.java b/algorithms/Java/trees/Left-Leaf-Sum.java new file mode 100644 index 00000000..2e4299aa --- /dev/null +++ b/algorithms/Java/trees/Left-Leaf-Sum.java @@ -0,0 +1,95 @@ +package Trees.Left_Leaf_Sum; +/* Problem Statement: Given the root of a binary tree, return the sum of all left leaves. */ + +//class to create Tree +class TreeNode{ + int data; + TreeNode left,right; + + TreeNode(int data){ + this.data = data; + this.left = this.right = null; + } + } +class Tree{ + TreeNode root; + + public Tree() { + root=null; + } +} +public class LeftLeafSum { + + //method to check if a node is leaf or not + static boolean isLeaf(TreeNode root) + { + if (root == null) return false; + if (root.left == null && root.right == null) + return true; + + return false; + } + + //returns the sum of left leaves + public static int leftsum(TreeNode root){ + + int leftLeavesSum=0; + + //to avoid null pointer exception + if(root!=null) + { + + //if a node's left is a leaf then add its value + if( isLeaf(root.left) ) + leftLeavesSum+=root.left.data; + + //else go to left + else + leftLeavesSum+=leftsum(root.left); + + //and finally go to right + leftLeavesSum+=leftsum(root.right); + } + + return leftLeavesSum; + + + + + } + +public static void main(String[] args) { + Tree tree = new Tree(); + tree.root = new TreeNode(1); + tree.root.left = new TreeNode(2); + tree.root.right = new TreeNode(3); + tree.root.left.left = new TreeNode(7); + tree.root.left.right = new TreeNode(8); + tree.root.right.left = new TreeNode(81); + tree.root.right.right= new TreeNode(75); + + + int sumOfLeftLeaves = leftsum(tree.root); + System.out.println("sum of left leaves is "+sumOfLeftLeaves); +} +} + +/* + +Eg. Input:- + 1 + / \ + 2 3 + / \ / \ + 7 8 81 75 +Output:- 88 + +Explanation:-there are two left leaves(nodes which have no child) 7 and 81 respectively in the tree and their sum is 88 + +Time Complexity:- O(N), where n is number of nodes in Binary Tree. + + +Code Description:- A method isLeaf() which returns a boolean, is created to check if a node is leaf or not, is yes then add its +left.data, if not then recursively go to its left and then its right. + +*/ From 368ec2e1dbfdd6129801a025540839f0b2458341 Mon Sep 17 00:00:00 2001 From: Chris Morin <78628697+christophermorin@users.noreply.github.com> Date: Wed, 14 Sep 2022 17:48:19 -0300 Subject: [PATCH 90/91] fix (Java): random node of a binary tree link (#841) Co-authored-by: Ming Tsai <37890026+ming-tsai@users.noreply.github.com> --- algorithms/Java/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/algorithms/Java/README.md b/algorithms/Java/README.md index ce60dd93..91f5c09e 100644 --- a/algorithms/Java/README.md +++ b/algorithms/Java/README.md @@ -100,7 +100,7 @@ - [Zig-Zag Traversal of a Tree](trees/zig-zag-traversal.java) - [Min Heap](trees/MinHeap.java) - [Check Tree Traversal](trees/check-tree-traversal.java) -- [Random Node of a binary tree](tree-random-node.java) +- [Random Node of a binary tree](trees/tree-random-node.java) - [Left Leaf Sum of a Binary tree](trees/Left-Leaf-Sum.java) ## Backtracking From 8072446b24c70789b88d99910ea4c2783322bb18 Mon Sep 17 00:00:00 2001 From: Adelinked <95980174+Adelinked@users.noreply.github.com> Date: Sun, 25 Sep 2022 02:47:06 +0100 Subject: [PATCH 91/91] chore(JavaScript): add max heap (#842) --- algorithms/JavaScript/README.md | 4 + algorithms/JavaScript/src/heaps/max-heap.js | 155 ++++++++++++++++++++ 2 files changed, 159 insertions(+) create mode 100644 algorithms/JavaScript/src/heaps/max-heap.js diff --git a/algorithms/JavaScript/README.md b/algorithms/JavaScript/README.md index f20b4faa..705c22d0 100644 --- a/algorithms/JavaScript/README.md +++ b/algorithms/JavaScript/README.md @@ -44,3 +44,7 @@ ## Recursion - [Factorial](src/recursion/factorial.js) + +## Heaps + +- [Max Heap](src/heaps/max-heap.js) \ No newline at end of file diff --git a/algorithms/JavaScript/src/heaps/max-heap.js b/algorithms/JavaScript/src/heaps/max-heap.js new file mode 100644 index 00000000..c1a4a915 --- /dev/null +++ b/algorithms/JavaScript/src/heaps/max-heap.js @@ -0,0 +1,155 @@ + +// A binary heap is a partially ordered binary tree +// that satisfies the heap property. +// The heap property specifies a relationship between parent and child nodes. +// In a max heap, all parent nodes are greater than +// or equal to their child nodes. +// Heaps are represented using arrays because +// it is faster to determine elements position and it needs +// less memory space as we don't need to maintain references to child nodes. +// An example: +// consider this max heap: [null, 47, 15, 35, 10, 3, 0, 25, 1]. +// The root node is the first element 47. its children are 15 and 35. +// The general indexes formula for an element of index i are: +// the parent is at: Math.floor(i / 2) +// the left child is at: i * 2 +// the right child is at: i * 2 + 1 + +const isDefined = (value) => value !== undefined && value !== null; + +class MaxHeap { + constructor() { + this.heap = [null]; + } + + // Insert a new element method + // this is a recursive method, the algorithm is: + // 1. Add the new element to the end of the array. + // 2. If the element is larger than its parent, switch them. + // 3. Continue switching until the new element is either + // smaller than its parent or you reach the root of the tree. + + insert(value) { + // add the new element to the end of the array + this.heap.push(value); + const place = (index) => { + const parentIndex = Math.floor(index / 2); + if (parentIndex <= 0) return; + if (this.heap[index] > this.heap[parentIndex]) { + // the switch is made here + [this.heap[parentIndex], this.heap[index]] = [ + this.heap[index], + this.heap[parentIndex], + ]; + place(parentIndex); + } + }; + // we begin the tests from the new element we added + place(this.heap.length - 1); + }; + + // Print heap content method + print() { + return this.heap; + }; + + // Remove an element from the heap + // it's also a recursive method, the algorithm will reestablish + // the heap property after removing the root: + // 1. Move the last element in the heap into the root position. + // 2. If either child of the root is greater than it, + // swap the root with the child of greater value. + // 3. Continue swapping until the parent is greater than both + // children or you reach the last level in the tree. + + remove() { + // save the root value element because this method will return it + const removed = this.heap[1]; + // the last element of the array is moved to the root position + this.heap[1] = this.heap[this.heap.length - 1]; + // the last element is removed from the array + this.heap.splice(this.heap.length - 1, 1); + + const place = (index) => { + if (index === this.heap.length - 1) return; + const child1Index = 2 * index; + const child2Index = child1Index + 1; + const child1 = this.heap[child1Index]; + const child2 = this.heap[child2Index]; + let newIndex = index; + // if the parent is greater than its two children + // then the heap property is respected + if ( + (!isDefined(child1) || this.heap[newIndex] >= child1) && + (!isDefined(child2) || this.heap[newIndex] >= child2) + ) { + return; + } + // test if the parent is less than its left child + if (isDefined(child1) && this.heap[newIndex] < child1) { + newIndex = child1Index; + } + // test if the parent is less than its right child + if (isDefined(child2) && this.heap[newIndex] < child2) { + newIndex = child2Index; + } + // the parent is switched with the child of the biggest value + if (index !== newIndex) { + [this.heap[index], this.heap[newIndex]] = [ + this.heap[newIndex], + this.heap[index], + ]; + place(newIndex); + } + }; + // start tests from the beginning of the array + place(1); + return removed; + }; + + // Sort an array using a max heap + // the elements of the array to sort were previously added one by one + // to the heap using the insert method + // the sorted array is the result of removing the heap's elements one by one + // using the remove method until it is empty + sort() { + const arr = []; + while (this.heap.length > 1) { + arr.push(this.remove()); + } + return arr; + }; + // Verify the heap property of a given max heap + verifyHeap() { + const explore = (index) => { + if (index === this.heap.length - 1) return true; + const child1Index = 2 * index; + const child2Index = 2 * index + 1; + const child1 = this.heap[child1Index]; + const child2 = this.heap[child2Index]; + return ( + (!isDefined(child1) || + (this.heap[index] >= child1 && explore(child1Index))) && + (!isDefined(child2) || + (this.heap[index] >= child2 && explore(child2Index))) + ); + }; + return explore(1); + }; +} + +const test = new MaxHeap(); +test.insert(1); +test.insert(3); +test.insert(0); +test.insert(10); +test.insert(35); +test.insert(25); +test.insert(47); +test.insert(15); +// display heap elements +console.log(test.print()); +// verify heap property +console.log(test.verifyHeap()); +// display the sorted array +console.log(test.sort());