diff --git a/.github/workflows/codespell.yml b/.github/workflows/codespell.yml index f27a8ae2..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" --quiet-level=2 --skip="**/**/package-lock.json" + - 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" 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/ diff --git a/README.md b/README.md index 8d59a45b..3a653dde 100644 --- a/README.md +++ b/README.md @@ -12,7 +12,11 @@ Data structure and Algorithm (DSA) ## Explanations + - [English](./docs/en) +- [Español](./docs/es) +- [Português](./docs/pt) +- [Turkish](./docs/tr) - [繁體中文](./docs/zh-tw) - [日本語](./docs/ja) @@ -115,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 | @atin | -| Python | @Arsenic-ATG, @atin, @sridhar-5 | -| JavaScript | @ming-tsai | +| Programming Language | Users | +| -------------------- | ----------------------------------------------------------- | +| C or C++ | @Arsenic-ATG, @UG-SEP, @aayushjain7, @Ashborn-SM, @Ashad001 | +| Java | @TawfikYasser, @aayushjain7, @mohitchakraverty | +| C# | @ming-tsai, @Waqar-107 | +| Go | @ayo-ajayi | +| Python | @Arsenic-ATG, @sridhar-5 | +| JavaScript | @ming-tsai | ## Contributors diff --git a/algorithms/C/README.md b/algorithms/C/README.md index adb67ee7..f2391b1a 100644 --- a/algorithms/C/README.md +++ b/algorithms/C/README.md @@ -5,7 +5,11 @@ - [Even and Odd](arrays/even-and-odd.c) - [Unique Elements in an array](arrays/unique-elements-in-an-array.c) - [Reverse an array](arrays/reverse-array.c) +- [Shuffle an array](arrays/shuffle_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 @@ -33,12 +37,18 @@ - [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 - [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) @@ -47,6 +57,9 @@ - [Heap Sort](sorting/heap-sort.c) - [Selection Sort](sorting/selection-sort.c) - [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 @@ -74,4 +87,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/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 + +******************************************************************************/ diff --git a/algorithms/C/arrays/secondLargestElement.c b/algorithms/C/arrays/secondLargestElement.c new file mode 100644 index 00000000..34b81d12 --- /dev/null +++ b/algorithms/C/arrays/secondLargestElement.c @@ -0,0 +1,38 @@ +//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] 88 45 + +Time Compexity: O(n) +Space compexity: O(1) +*/ diff --git a/algorithms/C/arrays/shuffle_array.c b/algorithms/C/arrays/shuffle_array.c new file mode 100644 index 00000000..fa94cb1f --- /dev/null +++ b/algorithms/C/arrays/shuffle_array.c @@ -0,0 +1,54 @@ +/* + +[PROBLEM]: Given an array, of size n, shuffle it. + +[TIME COMPLEXITY]: O(N) + +[SAMPLE OF OUTPUT]: + +Before shuffling: +1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 +After shuffling: +9 6 4 10 11 15 5 3 12 1 7 14 2 8 13 + +*/ + +#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 (int i = 0; i < size; i++) { + swap(array + i, array + (rand() % size)); // Each element swaps with another random element + } +} + +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, 11, 12, 13, 14, 15}; + printf("Before shuffling:\n"); + print_array(array, 15); + + shuffle(array, 15); + printf("After shuffling:\n"); + print_array(array, 15); + + return 0; +} 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 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..2af27e9a --- /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 sequence 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..25ead35d --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/src/fib.c @@ -0,0 +1,92 @@ +#include"./fib.h" // NOLINT(build/include) +#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..febadaf1 --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/src/fib.h @@ -0,0 +1,23 @@ + +#ifndef ALGORITHMS_C_MATHS_FIBONACCI_NUMBER_SRC_FIB_H_ +#define ALGORITHMS_C_MATHS_FIBONACCI_NUMBER_SRC_FIB_H_ + +/** + * 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 // 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 new file mode 100644 index 00000000..7e0759db --- /dev/null +++ b/algorithms/C/maths/fibonacci-number/src/main.c @@ -0,0 +1,23 @@ +#include +#include"./fib.h" // NOLINT(build/include) + +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; +} 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 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 + + | | | | | | | | | + | | | | | | | | | + | | | | | | | | ### + | | | | | ##### | | ##### +___###___#####_#######_ ___###_____|___#######_ __|________|_____#######__ + + +*/ 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; +} + 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 + +// 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) +*/ diff --git a/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp b/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp new file mode 100644 index 00000000..786c5a76 --- /dev/null +++ b/algorithms/CPlusPlus/Arrays/sparse_matrix.cpp @@ -0,0 +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. +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"< +#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/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/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); 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< +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<=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< +#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 +*/ + diff --git a/algorithms/CPlusPlus/Searching/binary-search.cpp b/algorithms/CPlusPlus/Searching/binary-search.cpp index 46cb09ee..c07771de 100644 --- a/algorithms/CPlusPlus/Searching/binary-search.cpp +++ b/algorithms/CPlusPlus/Searching/binary-search.cpp @@ -7,12 +7,15 @@ 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 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); 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: "< +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 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 diff --git a/algorithms/CSharp/README.md b/algorithms/CSharp/README.md index 821ca8b1..5f17d0b7 100644 --- a/algorithms/CSharp/README.md +++ b/algorithms/CSharp/README.md @@ -1,43 +1,57 @@ # 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) ## 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/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/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/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/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); + } + } +} 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))); + } + } +} 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 diff --git a/algorithms/Go/README.md b/algorithms/Go/README.md index 0e12c10e..680a3d30 100644 --- a/algorithms/Go/README.md +++ b/algorithms/Go/README.md @@ -19,11 +19,13 @@ ## 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) ## String - [Palindrome Permutation](strings/palindrome-permutation.go) +- [Anagram](strings/anagram.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 +} diff --git a/algorithms/Go/strings/anagram.go b/algorithms/Go/strings/anagram.go new file mode 100644 index 00000000..ca290e8d --- /dev/null +++ b/algorithms/Go/strings/anagram.go @@ -0,0 +1,50 @@ +/** +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 RunIsAnagram() { + 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 + + 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 +} 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 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 70c32fad..91f5c09e 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 @@ -74,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 @@ -88,6 +90,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 @@ -97,7 +100,8 @@ - [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 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= l) { - int mid = l + (r - l) / 2; - - // 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); + } + + } +} 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 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 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()); diff --git a/algorithms/JavaScript/src/index.js b/algorithms/JavaScript/src/index.js index f85a9fe7..b15a3328 100644 --- a/algorithms/JavaScript/src/index.js +++ b/algorithms/JavaScript/src/index.js @@ -4,6 +4,12 @@ require('./arrays/counting-inversions'); // Linked Lists require('./linked-lists/singly'); +// Maths +require('./maths/fibonacci-series'); + +// Recursion +require('./recursion/factorial'); + // Searching require('./searching/binary-search-recursive'); require('./searching/binary-search'); @@ -22,7 +28,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] 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 diff --git a/algorithms/Python/README.md b/algorithms/Python/README.md index 1b6b1eac..9bcc929b 100644 --- a/algorithms/Python/README.md +++ b/algorithms/Python/README.md @@ -5,11 +5,15 @@ - [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) +- [Dutch National Flag Algorithm](arrays/dutch_national_flag_algo.py) ## Linked Lists - [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) @@ -21,6 +25,9 @@ - [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) +- [GCD by Euclid's Algorithm](recursion/gcd_using_recursion.py) + ## Scheduling - [Interval Scheduling](scheduling/interval_scheduling.py) @@ -31,6 +38,8 @@ - [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) +- [Breath First Search](searching/breadth-first-search.py) ## Sorting - [Bubble Sort](sorting/bubble_sort.py) @@ -53,6 +62,8 @@ - [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) +- [Find all permutations](strings/find_all_permutations.py) ## Dynamic Programming - [Print Fibonacci Series Up To N-th Term](dynamic_programming/fibonacci_series.py) @@ -60,11 +71,19 @@ - [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) +- [BFS SEQUENCE](graphs/bfs-sequence.py) +- [Depth First Search](graphs/depth-first-search.py) ## Trees - [Binary Tree](trees/binary_tree.py) - [Binary Search Tree](trees/binary_search_tree.py) +## Queues +- [First in First out Queue](queues/fifo-queue.py) + +## Number Theory +- [Prime Number Checker](number_theory/prime_number.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)) 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)) + 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))) 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! +---------------------------------- +''' 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 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 + + 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)) 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. 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 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 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) 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]) + 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" 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 sinfo : + + 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) diff --git a/docs/en/README.md b/docs/en/README.md index aa1b5fd4..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) @@ -8,6 +12,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 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) 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/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/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/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..b144a2c8 --- /dev/null +++ b/docs/es/README.md @@ -0,0 +1,10 @@ +# Algoritmos + +## Ordenamiento +- [Ordenamiento de burbuja](./Ordenamiento/Bubble-Sort.md) +- [Ordenar por fusión](./Ordenamiento/Merge-Sort.md) +- [Ordenación rápida](./Ordenamiento/Quick-Sort.md) + +## Otro + +[Cómo agregar nueva documentación a un algoritmo?](./CONTRIBUTING.md) diff --git a/docs/ja/README.md b/docs/ja/README.md index 9ead69dd..27455842 100644 --- a/docs/ja/README.md +++ b/docs/ja/README.md @@ -1,4 +1,10 @@ # アルゴリズム + +## ソート + +- [バブルソート](./Sorting/Bubble-Sort.md) +- [挿入ソート](./Sorting/Insertion-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) 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) 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 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) + 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))