diff --git a/Backtracking/N-Queens.c b/Backtracking/N-Queens.c new file mode 100644 index 000000000..3094159dc --- /dev/null +++ b/Backtracking/N-Queens.c @@ -0,0 +1,73 @@ +#include +#define max 8 + +int n; +int board[8][8] = {{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}, +{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}, +{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}, +{0,0,0,0,0,0,0,0},{0,0,0,0,0,0,0,0}}; + +void printSolution() +{ + int i, j; + for(i = 0; i < n; i++) + { + for(j = 0; j < n; j++) + printf("%d ", board[i][j]); + printf("\n"); + } +} + +int isSafe(int row, int col) +{ + int i, j; + + for(i = 0; i < col; i++) + { + if(board[row][i]) + return 0; + } + + for(i=row, j=col; i>=0 && j>=0; i--, j--) + { + if(board[i][j]) + return 0; + } + + for(i=row, j=col; i=0; i++, j--) + { + if(board[i][j]) + return 0; + } +} + +int solveNQueens(int col) +{ + int i,j; + if(col>=n) + return 1; + + for(i = 0; i < n; i++) + { + if(isSafe(i, col)) + { + board[i][col] = 1; + + if(solveNQueens(col +1)) + return 1; + + board[i][col] = 0; + } + } + return 0; +} + +void main() +{ + printf("Enter the value of n: "); + scanf("%d", &n); + if(solveNQueens(0)==0) + printf("Solution does not exist.\n"); + else + printSolution(); +} diff --git a/Bit Manipulation/countSet/c/count-set-bits.c b/Bit Manipulation/countSet/c/count-set-bits.c new file mode 100644 index 000000000..e76b22c8f --- /dev/null +++ b/Bit Manipulation/countSet/c/count-set-bits.c @@ -0,0 +1,44 @@ +#include + +int countSimple(int n) { + int count = 0; + int iterations = 0; + + // Execute loop while there is any bit set + while (n) { + // If the last bit is set, add one to the counter + count += n & 0x1; + // Shift one place to the right + n >>= 1; + + iterations++; + } + + printf("Simple algorithm iterations: %d\n", iterations); + + return count; +} + +// Faster method, iterates exactly s times, where s is the number of bits set +int countBrianKenighan(int n) { + int count = 0; + + while (n) { + n &= n - 1; + count++; + } + + printf("Brian Kenighan's algorithm iterations: %d\n", count); + + return count; +} + +int main(void) { + int n1, n2; + int n = 0b101010101010; + + n1 = countSimple(n); + n2 = countBrianKenighan(n); + + printf("%d %d\n", n1, n2); +} diff --git a/Bit Manipulation/next power of 2/cpp/nextPowerof2.cpp b/Bit Manipulation/next power of 2/cpp/nextPowerof2.cpp index e48801cb8..a48225652 100644 --- a/Bit Manipulation/next power of 2/cpp/nextPowerof2.cpp +++ b/Bit Manipulation/next power of 2/cpp/nextPowerof2.cpp @@ -1,7 +1,7 @@ #include using namespace std; - +//function to calculate power of 2 unsigned int nextPowerOf2(unsigned int n){ unsigned int p = 1; if (n && !(n & (n - 1))) @@ -10,7 +10,7 @@ unsigned int nextPowerOf2(unsigned int n){ p <<= 1; return p; } - +//main function int main(){ int t; cin>>t; diff --git a/Dynamic Programming/Cutting Rod/cpp/cutting_rod.cpp b/Dynamic Programming/Cutting Rod/cpp/cutting_rod.cpp new file mode 100644 index 000000000..66184b6bb --- /dev/null +++ b/Dynamic Programming/Cutting Rod/cpp/cutting_rod.cpp @@ -0,0 +1,37 @@ +#include + +using namespace std; + +int extended_bottom_cut_rod(vector p, int n, vector &r, vector &s) { + for (int i = 1; i < n + 1; i++) { + int q = -1000000; + for (int j = 1; j < i + 1; j++) { + if(q < (p[j - 1] + r[i - j])) { + q = p[j - 1] + r[i - j]; + s[i] = j; + } + } + r[i] = q; + } + return r[n]; +} + +void print_cut_rod(vector p, int n) { + vector r(n + 1); vector s(n + 1); + int min_cut_cost = extended_bottom_cut_rod(p, n, r, s); + cout << min_cut_cost << endl; // print minimum cost to cut rod + // print steps of cutting rod + while(n > 0) { + cout << s[n] << " "; + n -= s[n]; + } +} + +int main() { + int n; cin >> n; + vector p(n); + for (int i = 0; i < n; i++) { + cin >> p[i]; + } + print_cut_rod(p, n); +} diff --git a/Dynamic Programming/Cutting Rod/python/cutting_rod.py b/Dynamic Programming/Cutting Rod/python/cutting_rod.py new file mode 100644 index 000000000..fdff7a8f5 --- /dev/null +++ b/Dynamic Programming/Cutting Rod/python/cutting_rod.py @@ -0,0 +1,31 @@ +# bottom-up rod cutting dp method +def min_rod_cutting_cost(p, n): + r = [0]*(n + 1) + for i in range(1, n + 1): + q = -1000000 + for j in range(1, i + 1): + q = max(q, p[j - 1] + r[i - j]) + r[i] = q + return r[n] + +def extended_bottom_cut_rod(p, n): + r, s = [0]*(n + 1), [0]*(n + 1) + for i in range(1, n + 1): + q = -1000000 + for j in range(1, i + 1): + if q < (p[j - 1] + r[i - j]): + q = (p[j - 1] + r[i - j]) + s[i] = j + r[i] = q + return (r, s) + +def print_cut_rod(p, n): + (r, s) = extended_bottom_cut_rod(p, n) + while n > 0: # print steps + print(s[n], end=" ") + n -= s[n] + +n = int(input()) +p = [int(x) for x in input().split()] +print(min_rod_cutting_cost(p, n)) # minimum cut rod cost +print_cut_rod(p, n) # steps to reach minimum cost diff --git a/Dynamic Programming/GameStrategy/MinimumNumberOfJumps.cpp b/Dynamic Programming/GameStrategy/MinimumNumberOfJumps.cpp new file mode 100644 index 000000000..871f359f4 --- /dev/null +++ b/Dynamic Programming/GameStrategy/MinimumNumberOfJumps.cpp @@ -0,0 +1,37 @@ +#include +#include + +int min(int x, int y) { return (x < y)? x: y; } + +int minJumps(int arr[], int n) +{ + int *jumps = new int[n]; + int i, j; + + if (n == 0 || arr[0] == 0) + return INT_MAX; + + jumps[0] = 0; + + for (i = 1; i < n; i++) + { + jumps[i] = INT_MAX; + for (j = 0; j < i; j++) + { + if (i <= j + arr[j] && jumps[j] != INT_MAX) + { + jumps[i] = min(jumps[i], jumps[j] + 1); + break; + } + } + } + return jumps[n-1]; +} + +int main() +{ + int arr[] = {1, 3, 6, 1, 0, 9}; + int size = sizeof(arr)/sizeof(int); + printf("Minimum number of jumps to reach end is %d ", minJumps(arr,size)); + return 0; +} diff --git a/Dynamic Programming/Longest Increasing Subsequence/cpp/longest_increasing_subsequence_bit.cpp b/Dynamic Programming/Longest Increasing Subsequence/cpp/longest_increasing_subsequence_bit.cpp new file mode 100644 index 000000000..684c13906 --- /dev/null +++ b/Dynamic Programming/Longest Increasing Subsequence/cpp/longest_increasing_subsequence_bit.cpp @@ -0,0 +1,42 @@ +// Longest Icreasing Subsequence with BIT +// O(NloN) complexity + +#include +#define MAXN 100005 +using namespace std; + +void update(int index, int val, int (&bit)[MAXN]) { + int size = sizeof(bit) / sizeof(*bit); + for (int i = index; i <= size; i += (i & -i)) { + bit[i] = max(bit[i], val); + } +} + +int getMax(int index, int (&bit)[MAXN]) { + int res = 0; + for (int i = index; i; i -= (i & -i)) { + res = max(res, bit[i]); + } + + return res; +} + +int findLISBit(int arr[],int length) { + int bit[MAXN]; + memset(bit, 0, sizeof bit); + + int res = 0; + + for (int i = 0; i < length; i++) { + int current = getMax(arr[i], bit); + update(arr[i], current + 1, bit); + } + + return getMax(MAXN - 5, bit); +} + +int main() { + int arr[] = { 1, 4, 2, 10, 8 }; + int lisLength = findLISBit(arr,5); + cout << "Longest Increasing Subsequence Length is : " << lisLength << endl; +} \ No newline at end of file diff --git a/Dynamic Programming/Longest Increasing Subsequence/go/longestIncreasingSubsequence.go b/Dynamic Programming/Longest Increasing Subsequence/go/longestIncreasingSubsequence.go new file mode 100644 index 000000000..4e3738236 --- /dev/null +++ b/Dynamic Programming/Longest Increasing Subsequence/go/longestIncreasingSubsequence.go @@ -0,0 +1,28 @@ +package main + +import ( + "fmt" + "math" +) + +func lis(arr []int64) int64 { + var ans int64 = 0 + dp := make([]int64, len(arr)) + for i := 0; i < len(arr); i++ { + dp[i] = 1 + for j := 0; j < i; j++ { + if arr[j] < arr[i] { + dp[i] = int64(math.Max(float64(dp[j]+1), float64(dp[i]))) + } + } + ans = int64(math.Max(float64(ans), float64(dp[i]))) + } + return ans +} + +func main() { + arr := make([]int64, 25, 50) + arr = []int64{10, 22, 9, 33, 21, 50, 41, 60, 80} + fmt.Println(lis(arr)) +} + diff --git a/Dynamic Programming/Longest Path Matrix/cpp/longPathMat.cpp b/Dynamic Programming/Longest Path Matrix/cpp/longPathMat.cpp new file mode 100644 index 000000000..5dfede55b --- /dev/null +++ b/Dynamic Programming/Longest Path Matrix/cpp/longPathMat.cpp @@ -0,0 +1,47 @@ +#include +#define max 1000 + +using namespace std; + +int findLongestFromACell(int i, int j, int mat[max][max], int dp[max][max], int n){ + if (i<0 || i>=n || j<0 || j>=n) + return 0; + if (dp[i][j] != -1) + return dp[i][j]; + if (j0 && (mat[i][j] +1 == mat[i][j-1])) + return dp[i][j] = 1 + findLongestFromACell(i,j-1,mat,dp); + if (i>0 && (mat[i][j] +1 == mat[i-1][j])) + return dp[i][j] = 1 + findLongestFromACell(i-1,j,mat,dp); + if (i>n; + for(int i=0;i>mat[i][j]; + } + } + cout << "Length of the longest path is "<< finLongestOverAll(mat, n)< longest: + lcs_set = set() + longest = c + lcs_set.add(string1[i-c+1:i+1]) + elif c == longest: + lcs_set.add(string1[i-c+1:i+1]) + + return lcs_set diff --git a/Dynamic Programming/fibonacci/go/fibonacci.go b/Dynamic Programming/fibonacci/go/fibonacci.go new file mode 100644 index 000000000..7afa6caa1 --- /dev/null +++ b/Dynamic Programming/fibonacci/go/fibonacci.go @@ -0,0 +1,27 @@ +package main + +import( + "fmt" +) + +var memo [] int64 //memoization array + +func fib(n int) int64 { + var f int64 + if memo[n-1] != 0 { + return memo[n-1] + } else if n <= 2 { + f = 1 + } else { + f = fib(n-1) + fib(n-2) + memo[n-1] = f + } + return f +} + +func main() { + n := 10 + memo = make([] int64, n) + fmt.Println(fib(n)) +} + diff --git a/Dynamic Programming/kadane/go/kadane.go b/Dynamic Programming/kadane/go/kadane.go new file mode 100644 index 000000000..da0c498e2 --- /dev/null +++ b/Dynamic Programming/kadane/go/kadane.go @@ -0,0 +1,27 @@ +package main + +import ( + "fmt" + "math" +) + +func kadane(arr []int64)int64{ + var currsum, maxsum int64 = 0, math.MinInt64 + for i := 0; i < len(arr); i++{ + currsum += arr[i] + if currsum > maxsum { + maxsum = currsum + } + if currsum < 0 { + currsum = 0 + } + } + return maxsum +} + +func main() { + arr:= make([]int64, 25, 50) + arr = []int64{-2, -3, 4, -1, -2, 1, 5, -3} + fmt.Println(kadane(arr)) +} + diff --git a/Greedy Algorithms/Fractional Knapsack/cpp/fractional_knapsack.cpp b/Greedy Algorithms/Fractional Knapsack/cpp/fractional_knapsack.cpp new file mode 100644 index 000000000..361233795 --- /dev/null +++ b/Greedy Algorithms/Fractional Knapsack/cpp/fractional_knapsack.cpp @@ -0,0 +1,43 @@ +#include + +using namespace std; + +double get_optimal_value(int capacity, vector weights, vector values) { + double value = 0.0; + int n = weights.size(); + for(int i = 1; i < n; i++) { + int w = weights[i]; + int v = values[i]; + double key = (double)v/w; + int j = i - 1; + while(j >= 0 && (double)values[j]/weights[j] < key) { + weights[j+1] = weights[j]; + values[j+1] = values[j]; + j--; + } + weights[j+1] = w; + values[j+1] = v; + } + for(int i = 0; i < n; i++) { + if(capacity == 0) { + return value; + } + int a = min(weights[i], capacity); + value += a*((double)values[i]/weights[i]); + weights[i] -= a; + capacity -= a; + } + return value; +} + +int main() { + int n; int capacity; + cin >> n >> capacity; + vector values(n); vector weights(n); + for (int i = 0; i < n; i++) { + cin >> values[i] >> weights[i]; + } + double optimal_value = get_optimal_value(capacity, weights, values); + cout << optimal_value << endl; + return 0; +} diff --git a/Greedy Algorithms/Largest Number/largest_number.py b/Greedy Algorithms/Largest Number/largest_number.py new file mode 100644 index 000000000..f54cf8454 --- /dev/null +++ b/Greedy Algorithms/Largest Number/largest_number.py @@ -0,0 +1,15 @@ +def largest_number(a): + res = "" + while a: + max_index = 0 + for i in range(1, len(a)): + if int(str(a[i]) + str(a[max_index])) > int(str(a[max_index]) + str(a[i])): + max_index = i + res += str(a[max_index]) + del a[max_index] + return res + +if __name__ == '__main__': + input = int(input()) # number of numbers in list + a = [int(x) for x in input().split()] # input list of numbers + print(largest_number(a)) diff --git a/Greedy Algorithms/OptimalStorageOnTapes.c b/Greedy Algorithms/OptimalStorageOnTapes.c new file mode 100644 index 000000000..79f4a1281 --- /dev/null +++ b/Greedy Algorithms/OptimalStorageOnTapes.c @@ -0,0 +1,90 @@ +#include + +void mergeSort(int a[10], int beg, int mid, int end) +{ + int i = beg, j = mid + 1, index = beg, temp[10], k; + while((i <= mid)&&(j <= end)) + { + if(a[i] mid) + { + while(j<=end) + { + temp[index] = a[j]; + index++; + j++; + } + } + else if(j > end) + { + while(i <= mid) + { + temp[index] = a[i]; + index++; + i++; + } + } + for(k=beg;k<=end;k++) + { + a[k]=temp[k]; + } +} + +void sort(int a[10], int beg, int end) +{ + int mid; + if(beg < end) + { + mid = (beg + end) / 2; + sort(a, 0, mid); + sort(a, mid + 1, end); + mergeSort(a, 0, mid, end); + } +} + +void main() +{ + int tape_length, lengths[10], n, sum = 0, i, j; + float mrt; + printf("Enter the Max Storage on the tape: "); + scanf("%d", &tape_length); + printf("Enter the no. of programs: "); + scanf("%d", %n); + printf("Enter the lengths of programs: "); + for(i=0;itape_length) + printf("Tape Length too small. Cannot Store all programs.\n"); + else + { + merge(lengths, 0, n-1); + for(i=0;i0;i--) + { + mrt += sum[j] - lengths[j]; + sum[j] -= lengths[j]; + }*/ + mrt = mrt / n; + printf("The Minimum Mean Retrieval Time is %f", mrt); + } +} diff --git a/Greedy Algorithms/minimum_number_of_coins.cpp b/Greedy Algorithms/minimum_number_of_coins.cpp new file mode 100644 index 000000000..5f534a52b --- /dev/null +++ b/Greedy Algorithms/minimum_number_of_coins.cpp @@ -0,0 +1,27 @@ +#include + using namespace std; + int deno[] = {1, 2, 5, 10, 20, 50, 100, 500, 1000}; //user defined denominations +int n = sizeof(deno)/sizeof(deno[0]); + void minChange(int m) +{ + vector v; + for (int i=n-1; i>=0; i--) + { + while (m>=deno[i]) + { + m-=deno[i]; + v.push_back(deno[i]); + } + } + for (int i = 0; i < v.size(); i++) + cout << v[i] << " "; +} + int main() +{ + int n; + cout<<"Enter a value n for which you want minimal number of change: "<<'\n'; + cin>>n; + cout << "Minimal number of change for " << n << " is "; + minChange(n); + return 0; +} diff --git a/Mathematics/Karatsuba/python/karatsuba.py b/Mathematics/Karatsuba/python/karatsuba.py new file mode 100644 index 000000000..f27dfcdf9 --- /dev/null +++ b/Mathematics/Karatsuba/python/karatsuba.py @@ -0,0 +1,18 @@ + +def karatsuba(a, b): + if len(str(a)) == 1 or len(str(b)) == 1: + return (a * b) + else: + m1 = max(len(str(a)), len(str(b))) + m2 = m1 // 2 + + a1 = x // 10**(m2) + a2 = x % 10**(m2) + b1 = y // 10**(m2) + b2 = y % 10**(m2) + + x = karatsuba(a2, b2) + y = karatsuba((a1 + a2), (b1 + b2)) + z = karatsuba(a1, b1) + + return ((z * 10**(2*m2)) + ((y - z - x) * 10**(m2)) + (x)) diff --git a/Mathematics/NChooseK/python/NChooseK.py b/Mathematics/NChooseK/python/NChooseK.py new file mode 100644 index 000000000..2e53fa5d2 --- /dev/null +++ b/Mathematics/NChooseK/python/NChooseK.py @@ -0,0 +1,12 @@ + +def bin_coeff(n, k): + ans = 1 + + if(k > (n-k)): + k = n-k + + for i in range(k): + ans *= (n - i) + ans /= (i + 1) + + return ans diff --git a/Mathematics/NChooseK/python/dp-binomial.py b/Mathematics/NChooseK/python/dp-binomial.py new file mode 100644 index 000000000..918a66a0b --- /dev/null +++ b/Mathematics/NChooseK/python/dp-binomial.py @@ -0,0 +1,12 @@ +def binomialCoeff(n, k): + st = [[0 for i in range(k + 1)] for j in range(n + 1)] + for i in range(n + 1): + for j in range(min(i, k) + 1): + if j == 0 or j == i: + st[i][j] = 1 + else: + st[i][j] = st[i - 1][j - 1] + st[i - 1][j] + return st[n][k] + +n, k = map(int, input().split()) +print(binomialCoeff(n, k)) diff --git a/Mathematics/NChooseK/python/recursive-binomial.py b/Mathematics/NChooseK/python/recursive-binomial.py new file mode 100644 index 000000000..ed09d6274 --- /dev/null +++ b/Mathematics/NChooseK/python/recursive-binomial.py @@ -0,0 +1,7 @@ +def binomialCoeff(n, k): + if k == n or k == 0: + return 1 + return binomialCoeff(n - 1, k) + binomialCoeff(n - 1, k - 1) + +n, k = map(int, input().split()) +print(binomialCoeff(n, k)) diff --git a/Mathematics/euclidean distance/euclidean_distance.cpp b/Mathematics/euclidean distance/euclidean_distance.cpp new file mode 100644 index 000000000..b46ce25af --- /dev/null +++ b/Mathematics/euclidean distance/euclidean_distance.cpp @@ -0,0 +1,19 @@ +#include +#include + +double euclidean_distance(double x_pos[], double y_pos[], int space_dimension){ + double result = 0; + for(int i = 0; i < space_dimension; i++){ + result += pow(x_pos[i] - y_pos[i],2); + } + return sqrt(result); +} + + +int main(int argc, const char * argv[]) { + double x[] = {0,0,0}; + double y[] = {1,1,1}; + std::cout << euclidean_distance(x, y, 3); + + return 0; +} diff --git a/Mathematics/factorial/cpp/factorial.cpp b/Mathematics/factorial/cpp/factorial.cpp new file mode 100644 index 000000000..7f65fbbb1 --- /dev/null +++ b/Mathematics/factorial/cpp/factorial.cpp @@ -0,0 +1,14 @@ +#include +using namespace std; + +long long factorial(int n) { + if(n <= 1) { + return 1; + } + return n * factorial(n - 1); +} + +int main() { + int n; cin >> n; + cout << factorial(n); +} diff --git a/Mathematics/factorial/cpp/factorial.exe b/Mathematics/factorial/cpp/factorial.exe new file mode 100644 index 000000000..e42b61b11 Binary files /dev/null and b/Mathematics/factorial/cpp/factorial.exe differ diff --git a/Mathematics/factorial/java/Factorial.java b/Mathematics/factorial/java/Factorial.java new file mode 100644 index 000000000..5bd4d76da --- /dev/null +++ b/Mathematics/factorial/java/Factorial.java @@ -0,0 +1,18 @@ +import java.util.*; +import java.io.*; +class Factorial { + public static void main(String[] args) { + Scanner sc = new Scanner(System.in); + int n = sc.nextInt(); + System.out.println("the factorial of this number is: " + factorial(n)); + } + + //a recursive function to calculate n! + public int factorial(int n){ + if(n==0) + return 1; + else + return n*factorial(n-1); + } +} + diff --git a/Mathematics/factorial/python/factorial.py b/Mathematics/factorial/python/factorial.py new file mode 100644 index 000000000..ff0796ae5 --- /dev/null +++ b/Mathematics/factorial/python/factorial.py @@ -0,0 +1,11 @@ +# Python Program to Compute the Factorial of a Number + +def factorial(num): + if (num < 0): + return + if (num == 1): + return 1 + return num * factorial(num - 1) + +print("5! is" + str(factorial(5))) +print("10! is " + str(factorial(10))) diff --git a/Mathematics/fibonacci/cpp/constexpr-fibonacci.cpp b/Mathematics/fibonacci/cpp/constexpr-fibonacci.cpp new file mode 100644 index 000000000..6fc38470d --- /dev/null +++ b/Mathematics/fibonacci/cpp/constexpr-fibonacci.cpp @@ -0,0 +1,17 @@ +// Computes a specific index of the Fibonacci sequence +// Can be computed at compile-time under certain conditions + +constexpr unsigned int fibonacci(unsigned int index) { + + constexpr auto gr = (1 + std::sqrt(5)) / 2; + + if(index == 0) { + return 0; + } else if(index == 1) { + return 1; + } + + return static_cast( + (std::pow(gr, index) - std::pow(1 - gr, index)) / sqrt(5) + ); +} diff --git a/Mathematics/fibonacci/go/fibonacci.go b/Mathematics/fibonacci/go/fibonacci.go new file mode 100644 index 000000000..cc27be891 --- /dev/null +++ b/Mathematics/fibonacci/go/fibonacci.go @@ -0,0 +1,23 @@ +package main + +import( + "fmt" +) + +func fib(x int) int { + //Thus function finds the xth number of the fibonacci sequence + if x < 3 { + return 1 + } + return fib(x-1)+fib(x-2) +} + +func main(){ + var input int + fmt.Println("The Point of this program is to compute fibonacci. Please enter a number") + _,err := fmt.Scanf("%d",&input) + if err != nil { + fmt.Println("Invalid input") + } + fmt.Printf("The fibbonacci at %d is %d\n",input,fib(input)) +} diff --git a/Mathematics/harmonic mean/cpp/harmonic-mean.cpp b/Mathematics/harmonic mean/cpp/harmonic-mean.cpp new file mode 100644 index 000000000..8290bfa35 --- /dev/null +++ b/Mathematics/harmonic mean/cpp/harmonic-mean.cpp @@ -0,0 +1,12 @@ +#include +using namespace std; + +double harmonic(int a, int b) { + return (double)(2*a*b)/(a + b); +} + +int main() { + int a, b; cin >> a >> b; + cout << harmonic(a, b); + return 0; +} diff --git a/Mathematics/harmonic mean/python/harmonic_mean.py b/Mathematics/harmonic mean/python/harmonic_mean.py new file mode 100644 index 000000000..2b20f87da --- /dev/null +++ b/Mathematics/harmonic mean/python/harmonic_mean.py @@ -0,0 +1,5 @@ +def harmonic(a, b): + return (2*a*b)/(a + b); + +a, b = map(int, input().split()) +print(harmonic(a, b)) diff --git a/Mathematics/log 2 n/python/log2n.py b/Mathematics/log 2 n/python/log2n.py new file mode 100644 index 000000000..fe347f05f --- /dev/null +++ b/Mathematics/log 2 n/python/log2n.py @@ -0,0 +1,7 @@ +# Python Program to find Log Base 2 of a number + +def getlogbase2n(n): + desired_value = log(n) / log(2) + return desired_value + +print("The log base 2 of 32 is " + str(getlogbase2n(32))) diff --git a/Mathematics/reverse number/reverse-number.cpp b/Mathematics/reverse number/reverse-number.cpp new file mode 100644 index 000000000..21a84a259 --- /dev/null +++ b/Mathematics/reverse number/reverse-number.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; + +long long reverse_number(long long n) { + long long res = 0; + while(n > 0) { + res = res*10 + n % 10; + n /= 10; + } + return res; +} + +int main() { + long long n; cin >> n; + cout << reverse_number(n); +} diff --git a/Mathematics/reverse number/reverse-number.py b/Mathematics/reverse number/reverse-number.py new file mode 100644 index 000000000..a9d4b366b --- /dev/null +++ b/Mathematics/reverse number/reverse-number.py @@ -0,0 +1,9 @@ +def reverse_number(n): + res = 0 + while n > 0: + res = res*10 + n % 10 + n //= 10 + return res + +inp = int(input()) +print(reverse_number(inp)) diff --git a/Mathematics/sieve of Eratosthenes/python/sieve-of-eratosthenes.py b/Mathematics/sieve of Eratosthenes/python/sieve-of-eratosthenes.py new file mode 100644 index 000000000..4acff4054 --- /dev/null +++ b/Mathematics/sieve of Eratosthenes/python/sieve-of-eratosthenes.py @@ -0,0 +1,13 @@ +n = int(input()) +prime = [1]*(n + 1) + +p = 2 +while p*p <= n: + if prime[p] == 1: + for i in range(p*2, n + 1, p): + prime[i] = 0 + p+= 1 + +for i in range(2, n + 1): + if prime[i] == 1: + print("p = " + str(i)) diff --git a/Other Algorithms/KMP/golang/README.md b/Other Algorithms/KMP/golang/README.md new file mode 100644 index 000000000..9547f590b --- /dev/null +++ b/Other Algorithms/KMP/golang/README.md @@ -0,0 +1,7 @@ +# KMP Algorithm for Pattern searching +The Knuth–Morris–Pratt string-searching algorithm searches for the occurrence of a pattern of string in a text. +The main idea behind this algorithm is that when a mismatch occurs, the pattern itself gives sufficient information to check where the next match may occur. This reduces the number of comparisons among the characters of pattern and text. + +It works on a worst case complexity of O(n). + +The algorithm above has been compiled via resources from [GeeksforGeeks](https://www.geeksforgeeks.org/kmp-algorithm-for-pattern-searching/) diff --git a/Other Algorithms/KMP/golang/kmp.go b/Other Algorithms/KMP/golang/kmp.go new file mode 100644 index 000000000..a7d6e936e --- /dev/null +++ b/Other Algorithms/KMP/golang/kmp.go @@ -0,0 +1,84 @@ +//Implementation of Knuth Morris Pratt (KMP) algorithm for pattern searching + +// Author: Saloni Rajeev Kumar +// Date: Oct 7, 2018 + +package main +import ( + "fmt" + "bufio" + "os" +) + +var flag = 0 + +func calculate_lps(pat string, m int, lps []int){ + len := 0 // length of the previous longest suffix + lps[0] = 0 + + i:=1 + for i + +using namespace std; + +int kadane(vector a) { + int max_current = a[0]; + int max_global = a[0]; + for (int i = 1; i < a.size(); i++) { + max_current = max(a[i], max_current + a[i]); + if(max_current > max_global) { + max_global = max_current; + } + } + return max_global; +} + +int main() { + int n; cin >> n; + vector a(n); + for (int i = 0; i < n; ++i) { + cin >> a[i]; + } + cout << kadane(a); + return 0; +} diff --git a/Other Algorithms/Kadane Algorithm/python/kadane.py b/Other Algorithms/Kadane Algorithm/python/kadane.py new file mode 100644 index 000000000..5e0936e5e --- /dev/null +++ b/Other Algorithms/Kadane Algorithm/python/kadane.py @@ -0,0 +1,11 @@ +def kadane(a): + max_current = max_global = a[0] + for i in range(1, len(a)): + max_current = max(a[i], max_current + a[i]) + if max_current > max_global: + max_global = max_current + return max_global + +n = int(input()) +a = [int(x) for x in input().split()] +print(kadane(a)) diff --git a/Other Algorithms/Reverse Number/rev.py b/Other Algorithms/Reverse Number/rev.py new file mode 100644 index 000000000..fe98d65c2 --- /dev/null +++ b/Other Algorithms/Reverse Number/rev.py @@ -0,0 +1,5 @@ +#Python3 program to take a number as an input and display it reversed using string slicing +num=input() +aux=str(num)[::-1] +reverse=int(aux) +print(reverse) \ No newline at end of file diff --git a/Other Algorithms/Reverse Number/rev2.py b/Other Algorithms/Reverse Number/rev2.py new file mode 100644 index 000000000..3269ff3fc --- /dev/null +++ b/Other Algorithms/Reverse Number/rev2.py @@ -0,0 +1,8 @@ +#Python3 program to take a number as an input and display it reversed using string manipulation +num=input() +aux=str(num) +i="" +for character in aux: + i=character+i +reverse=int(i) +print(reverse) diff --git a/Other Algorithms/String/python/string_reverse.py b/Other Algorithms/String/python/string_reverse.py new file mode 100644 index 000000000..a1806ce30 --- /dev/null +++ b/Other Algorithms/String/python/string_reverse.py @@ -0,0 +1,2 @@ +def reverse_string(word): + return word[::-1] diff --git a/Other Algorithms/heapsort.cs b/Other Algorithms/heapsort.cs new file mode 100644 index 000000000..5c1ccf618 --- /dev/null +++ b/Other Algorithms/heapsort.cs @@ -0,0 +1,117 @@ +using System; + +namespace Heap_sort +{ + public class MainClass + { + public static void Main (string[] args) + { + int[] mykeys = new int[] {2, 5, -4, 11, 0, 18, 22, 67, 51, 6}; + + //double[] mykeys = new double[] {2.22, 0.5, 2.7, -1.0, 11.2}; + + //string[] mykeys = new string[] {"Red", "White", "Black", "Green", "Orange"}; + + Console.WriteLine("\nOriginal Array Elements :"); + printArray (mykeys); + + heapSort (mykeys); + + Console.WriteLine("\n\nSorted Array Elements :"); + printArray (mykeys); + Console.WriteLine("\n"); + } + + private static void heapSort (T[] array) where T : IComparable + { + int heapSize = array.Length; + + buildMaxHeap (array); + + for (int i = heapSize-1; i >= 1; i--) + { + swap (array, i, 0); + heapSize--; + sink (array, heapSize, 0); + } + } + + private static void buildMaxHeap (T[] array) where T : IComparable + { + int heapSize = array.Length; + + for (int i = (heapSize/2) - 1; i >= 0; i--) + { + sink (array, heapSize, i); + } + } + + private static void sink (T[] array, int heapSize, int toSinkPos) where T : IComparable + { + if (getLeftKidPos (toSinkPos) >= heapSize) + { + // No left kid => no kid at all + return; + } + + + int largestKidPos; + bool leftIsLargest; + + if (getRightKidPos (toSinkPos) >= heapSize || array [getRightKidPos (toSinkPos)].CompareTo (array [getLeftKidPos (toSinkPos)]) < 0) + { + largestKidPos = getLeftKidPos (toSinkPos); + leftIsLargest = true; + } else + { + largestKidPos = getRightKidPos (toSinkPos); + leftIsLargest = false; + } + + + + if (array [largestKidPos].CompareTo (array [toSinkPos]) > 0) + { + swap (array, toSinkPos, largestKidPos); + + if (leftIsLargest) + { + sink (array, heapSize, getLeftKidPos (toSinkPos)); + + } else + { + sink (array, heapSize, getRightKidPos (toSinkPos)); + } + } + + } + + private static void swap (T[] array, int pos0, int pos1) + { + T tmpVal = array [pos0]; + array [pos0] = array [pos1]; + array [pos1] = tmpVal; + } + + private static int getLeftKidPos (int parentPos) + { + return (2 * (parentPos + 1)) - 1; + } + + private static int getRightKidPos (int parentPos) + { + return 2 * (parentPos + 1); + } + + private static void printArray (T[] array) + { + + foreach (T t in array) + { + Console.Write(' '+t.ToString()+' '); + } + + } + } + +} diff --git a/Other Algorithms/union_find/union_find.cpp b/Other Algorithms/union_find/union_find.cpp new file mode 100644 index 000000000..a150efddc --- /dev/null +++ b/Other Algorithms/union_find/union_find.cpp @@ -0,0 +1,45 @@ +/* +* Algorithm that merges two disjointed sets and can find +* what set each element is. +*/ + +#include +#define MAXN 10010 + +using namespace std; + +// Declare the variables that will store the fathers and the ranks of each element. + +int father[MAXN], rank[MAXN]; + +int find(int x){ + + if(father[x] == x) return x; + + return father[x] = find(father[x]); + +} + +void merge(int x, int y){ + + x = find(x); + y = find(y); + + if(x == y) return; + + if(rank[x] > rank[y]){ + father[y] = x; + } + + else{ + father[x] = y; + if(rank[x] == rank[y]) rank[y]++; + } +} + + +// Initializes each father to itself and rank to 0 +int init(){ + memset(rank,0,sizeof(rank)); + for(int i = 1; i <= MAXN-1;++i) pai[i] = i; +} \ No newline at end of file diff --git a/Random Number/random.R b/Random Number/random.R new file mode 100644 index 000000000..54fe850a4 --- /dev/null +++ b/Random Number/random.R @@ -0,0 +1,17 @@ +## 500 random numbers with normal distribution +rnorm(500) + +#Random number with normal distribution using mean and standard deviation +rnorm(500,mean=10,sd=1); + +# 500 random numbers between 0 and 100 +runif(500, min=0, max=100); + +#Random sample of 3 numbers in the range of 0 to 100 with replacement +sample(1:100, 3, replace=TRUE) + +#visualize numbers distribution in a histogram +hist(rnorm(500)); + +#density +plot(density(runif(500, min=0, max=100))); \ No newline at end of file diff --git a/Recursive Algorithms/DFS/Python/dfs_graph.py b/Recursive Algorithms/DFS/Python/dfs_graph.py new file mode 100644 index 000000000..f4bddd732 --- /dev/null +++ b/Recursive Algorithms/DFS/Python/dfs_graph.py @@ -0,0 +1,29 @@ +class Graph(object): + def __init__(self, vertices): + self.vertices = vertices + self.adjacency = [[] for _ in range(vertices)] + + def addEdge(self, i, vertex): + self.adjacency[i].append(vertex) + + def dfs(self, vertex): + visited = [False for _ in range(self.vertices)] + self._dfs(vertex, visited) + + def _dfs(self, vertex, visited): + print(vertex) + visited[vertex] = True + for i in self.adjacency[vertex]: + if not visited[i]: + self._dfs(i, visited) + +# Testing the code, values taken from https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/ +g = Graph(4) +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(2, 3) +g.addEdge(3, 3) +print('Following is Depth First Traversal (starting from vertex 2)') +g.dfs(2) \ No newline at end of file diff --git a/Recursive Algorithms/DFS/Ruby/graph_dfs.rb b/Recursive Algorithms/DFS/Ruby/graph_dfs.rb new file mode 100644 index 000000000..de6920b1b --- /dev/null +++ b/Recursive Algorithms/DFS/Ruby/graph_dfs.rb @@ -0,0 +1,44 @@ +class Graph + # builds a graph with the specified number of vertices. + def initialize(vertices) + @vertices = vertices + @adjacency = vertices.times.collect{[]} + end + + def addEdge(i, vertex) + adjacency[i].push(vertex) + end + + def dfs(element) + visited = vertices.times.collect{false} + dfs_run(element, visited) + end + + + private + + def dfs_run(v, visited) + puts v + visited[v] = true + adjacency[v].each do |vertex| + if not visited[vertex] + dfs_run(vertex, visited) + end + end + end + + attr_reader :vertices, :adjacency +end + +# Testing the code, values taken from https://www.geeksforgeeks.org/depth-first-search-or-dfs-for-a-graph/ +g = Graph.new(4) +g.addEdge(0, 1) +g.addEdge(0, 2) +g.addEdge(1, 2) +g.addEdge(2, 0) +g.addEdge(2, 3) +g.addEdge(3, 3) + +puts "Following is Depth First Traversal (starting from vertex 2)" + +g.dfs(2) \ No newline at end of file diff --git a/Recursive Algorithms/DFS/c++ recursive spiral level order tree traversal b/Recursive Algorithms/DFS/c++ recursive spiral level order tree traversal new file mode 100644 index 000000000..bc6b824fe --- /dev/null +++ b/Recursive Algorithms/DFS/c++ recursive spiral level order tree traversal @@ -0,0 +1,110 @@ +// Recursive C program for level order traversal of Binary Tree +#include +#include + +/* A binary tree node has data, pointer to left child + and a pointer to right child */ +struct node +{ + int data; + struct node* left, *right; +}; + +/* Function protoypes */ +void printGivenLevel(struct node* root, int level,int counter); +int height(struct node* node); +struct node* newNode(int data); + +/* Function to print level order traversal a tree*/ +void printLevelOrder(struct node* root) +{ + int h = height(root); + int i,j; + for (i=1; i<=h; i++){ + j=i; + printGivenLevel(root,i,j); +} +} +/* Print nodes at a given level */ +void printGivenLevel(struct node* root, int level ,int counter) +{ + if (root == NULL) + return; + if (level == 1) + printf("%d ", root->data); + + else if (level > 1 && (counter%2)!=0) + { + printGivenLevel(root->right, level-1,counter); + printGivenLevel(root->left, level-1,counter); + } + + else + { + printGivenLevel(root->left, level-1,counter); + printGivenLevel(root->right, level-1,counter); + } +} + +/* Compute the "height" of a tree -- the number of + nodes along the longest path from the root node + down to the farthest leaf node.*/ +int height(struct node* node) +{ + if (node==NULL) + return 0; + else + { + /* compute the height of each subtree */ + int lheight = height(node->left); + int rheight = height(node->right); + + /* use the larger one */ + if (lheight > rheight) + return(lheight+1); + else return(rheight+1); + } +} + +/* Helper function that allocates a new node with the + given data and NULL left and right pointers. */ +struct node* newNode(int data) +{ + struct node* node = (struct node*) + malloc(sizeof(struct node)); + node->data = data; + node->left = NULL; + node->right = NULL; + + return(node); +} + +/* Driver program to test above functions*/ +int main() +{ + struct node *root = newNode(1); + root->left = newNode(2); + root->right = newNode(3); + root->right->left = newNode(1); + root->right->right= newNode(9); + root->left->left = newNode(4); + root->left->right = newNode(5); + root->left->left->left = newNode(6); + root->left->right->left = newNode(8); + root->left->right->left->left= newNode(0); + + root->left->right->left->right= newNode(3); + root->left->right->left->right->left= newNode(7); + root->left->right->left->right->right= newNode(5); + root->left->right->left->right->left->left= newNode(9); + root->left->right->left->right->left->right= newNode(6); + + + printf("Level Order traversal of binary tree is \n"); +/*int l; + l=height(root); +printf("%d",l); + */ + printLevelOrder(root); + return 0; +} diff --git a/Recursive Algorithms/Majority Element/python/majority_element.py b/Recursive Algorithms/Majority Element/python/majority_element.py new file mode 100644 index 000000000..342fe9c9e --- /dev/null +++ b/Recursive Algorithms/Majority Element/python/majority_element.py @@ -0,0 +1,21 @@ +def get_majority(a): + n = len(a) + if n == 1: + return a[0] + k = n // 2 + left_major = get_majority(a[:k]) + right_major = get_majority(a[k:]) + if left_major == right_major: + return left_major + left_count = sum(1 for i in a if i == left_major) + right_count = sum(1 for i in a if i == right_major) + if left_count > k: + return left_major + elif right_count > k: + return right_major + else: + return -1 + +n = int(input()) +a = [int(x) for x in input().split()] +print(get_majority(a)) diff --git a/Recursive Algorithms/MaximumSubarray/cpp/maximum_subarray.cpp b/Recursive Algorithms/MaximumSubarray/cpp/maximum_subarray.cpp new file mode 100644 index 000000000..89dde3282 --- /dev/null +++ b/Recursive Algorithms/MaximumSubarray/cpp/maximum_subarray.cpp @@ -0,0 +1,61 @@ +#include + +using namespace std; + +vector find_max_crossing_subarray(vector A, int low, int mid, int high) { + // res[0] is max_left index, res[1] is max_right index, res[2] is the max sum value + vector res(3); + int sum = 0; int left_sum = -1000000; int right_sum = -1000000; + for (int i = mid; i > low - 1; i--) { + sum += A[i]; + if(sum > left_sum) { + left_sum = sum; + res[0] = i; + } + } + sum = 0; + for (int i = mid + 1; i < high + 1; i++) { + sum += A[i]; + if(sum > right_sum) { + right_sum = sum; + res[1] = i; + } + } + res[2] = left_sum + right_sum; + return res; +} + +vector find_max_subarray(vector A, int low, int high) { + if(high == low) { + vector res(3); + res[0] = low; res[1] = high; res[2] = A[low]; + return res; + } + int mid = (low + high)/2; + vector res(3); + vector left_res = find_max_subarray(A, low, mid); + vector right_res = find_max_subarray(A, mid + 1, high); + vector cross_res = find_max_crossing_subarray(A, low, mid, high); + + if(left_res[2] >= right_res[2] && left_res[2] >= cross_res[2]) { + res = left_res; + } + else if(right_res[2] >= left_res[2] && right_res[2] >= cross_res[2]) { + res = right_res; + } + else { + res = cross_res; + } + return res; +} + +int main() { + int n; cin >> n; + vector A(n); + for (int i = 0; i < n; ++i) { + cin >> A[i]; + } + vector res = find_max_subarray(A, 0, n - 1); + cout << res[0] << " " << res[1] << " " << res[2]; + return 0; +} diff --git a/Recursive Algorithms/MaximumSubarray/python/maximum_subarray.py b/Recursive Algorithms/MaximumSubarray/python/maximum_subarray.py new file mode 100644 index 000000000..0188e726a --- /dev/null +++ b/Recursive Algorithms/MaximumSubarray/python/maximum_subarray.py @@ -0,0 +1,34 @@ +# Time complexity: O(nlogn) +def find_max_crossing_subarray(A, low, mid, high): + sum, left_sum = 0, -1000000000000 + for i in range(mid, low - 1, -1): + sum += A[i] + if sum > left_sum: + left_sum = sum + max_left = i + sum, right_sum = 0, -1000000000000 + for i in range(mid + 1, high + 1): + sum += A[i] + if sum > right_sum: + right_sum = sum + max_right = i + return (max_left, max_right, left_sum + right_sum) + +def find_max_subarray(A, low, high): + if high == low: + return (low, high, A[low]) + mid = (low + high) // 2 + left_low, left_high, left_sum = find_max_subarray(A, low, mid) + right_low, right_high, right_sum = find_max_subarray(A, mid + 1, high) + cross_low, cross_high, cross_sum = find_max_crossing_subarray(A, low, mid, high) + if left_sum >= right_sum and left_sum >= cross_sum: + return (left_low, left_high, left_sum) + elif right_sum >= left_sum and right_sum >= cross_sum: + return (right_low, right_high, right_sum) + else: + return (cross_low, cross_high, cross_sum) + +n = int(input()) +A = [int(x) for x in input().split()] +low, high, sum = find_max_subarray(A, 0, n - 1) +print(low, high, sum) diff --git a/Searching/Interpolation Search/python/interpolation_search.py b/Searching/Interpolation Search/python/interpolation_search.py new file mode 100644 index 000000000..8445d23e4 --- /dev/null +++ b/Searching/Interpolation Search/python/interpolation_search.py @@ -0,0 +1,13 @@ + +def interpolation_search(list, key): + lo = 0 + hi = len(list) - 1 + while(lo <= hi and key >= list[lo] and key <= list[hi]): + pos = lo + (((hi - lo)/(list[hi]-list[lo]))*(key - list[lo])) + if(list[pos]==x): + return pos + elif(list[pos] < x): + lo = pos + 1 + else: + hi = pos - 1 + return -1 diff --git a/Searching/Linear Search/linear_search.py b/Searching/Linear Search/linear_search.py new file mode 100644 index 000000000..442552ae4 --- /dev/null +++ b/Searching/Linear Search/linear_search.py @@ -0,0 +1,6 @@ + +def linear_search(list, key): + for i in range(len(list)): + if(list[i] == key): + return i + return -1 diff --git a/Searching/binary search/cpp/RangeSearch.cpp b/Searching/binary search/cpp/RangeSearch.cpp new file mode 100644 index 000000000..cb3f4ccc3 --- /dev/null +++ b/Searching/binary search/cpp/RangeSearch.cpp @@ -0,0 +1,65 @@ +// Find the range of a particular element occuring in a given sorted array. +// If the element doesn't exist, return 1. + +#include + +using namespace std; + +int findleft(const vector& A, int B, int low, int high){ + int res = -1; + while(low <= high){ + int mid = low + (high - low)/2; + if(A[mid] == B){ + res = mid; + high = mid-1; + }else if(A[mid] < B){ + low = mid+1; + }else high = mid-1; + } + if(res == -1) + return res; + return low; +} + +int findright(const vector& A, int B, int low, int high){ + int res = -1; + while(low <= high){ + int mid = low + (high - low)/2; + if(A[mid] == B){ + res = mid; + low = mid+1; + }else if(A[mid] > B){ + high = mid-1; + }else low = mid+1; + } + if(res == -1)return -1; + return low-1; +} + +int main(int argc, char const *argv[]) +{ + std::vector v({1,2,2,3,3,3,4,4,4,4,5,6,7,8,8,8,8,8}); + + cout << "The input vector is: " << endl; + for(auto i: v){ + cout << i << " "; + } + cout << endl; + + cout << "The first and last index of occurance of element '8' is : " << findleft(v, 8, 0, v.size()-1) + << " " + << findright(v, 8, 0, v.size()-1) + << endl; + + cout << "The first and last index of occurance of element '1' is : " << findleft(v, 1, 0, v.size()-1) + << " " + << findright(v, 1, 0, v.size()-1) + << endl; + + cout << "The first and last index of occurance of element '10' is : " << findleft(v, 10, 0, v.size()-1) + << " " + << findright(v, 10, 0, v.size()-1) + << endl; + + return 0; +} \ No newline at end of file diff --git a/Searching/string search/boyer-moore-horspool/cpp/bm-horspool.cpp b/Searching/string search/boyer-moore-horspool/cpp/bm-horspool.cpp new file mode 100644 index 000000000..00f4ad2e9 --- /dev/null +++ b/Searching/string search/boyer-moore-horspool/cpp/bm-horspool.cpp @@ -0,0 +1,29 @@ +#include +#include +#include +#include + +uint8_t* bm_horspool(uint8_t *source, const char* pattern, uint32_t size, uint32_t pattern_size) { + + if(pattern_size > size) + return nullptr; + + std::array lookup_table; + std::fill(lookup_table.begin(), lookup_table.end(), pattern_size); + + for(uint32_t i = 0; i < pattern_size - 1; i++) + lookup_table[pattern[i]] = pattern_size - i - 1; + + uint32_t offset = 0; + while(offset <= size - pattern_size) + { + uint8_t c = source[offset + pattern_size - 1]; + if(pattern[pattern_size - 1] == c && + std::memcmp(pattern, source + offset, pattern_size - 1) == 0) + return source + offset; + + offset += lookup_table[c]; + } + + return nullptr; +} diff --git a/Sorting/Heap Sort/cpp/a.out b/Sorting/Heap Sort/cpp/a.out new file mode 100755 index 000000000..1200f2ff6 Binary files /dev/null and b/Sorting/Heap Sort/cpp/a.out differ diff --git a/Sorting/Heap Sort/cpp/heapsort.cpp b/Sorting/Heap Sort/cpp/heapsort.cpp new file mode 100644 index 000000000..504fb0935 --- /dev/null +++ b/Sorting/Heap Sort/cpp/heapsort.cpp @@ -0,0 +1,68 @@ +// C++ program for implementation of Heap Sort +#include + +using namespace std; + +// To heapify a subtree rooted with node i which is +// an index in arr[]. n is size of heap +void heapify(int arr[], int n, int i) +{ + int largest = i; // Initialize largest as root + int l = 2*i + 1; // left = 2*i + 1 + int r = 2*i + 2; // right = 2*i + 2 + + // If left child is larger than root + if (l < n && arr[l] > arr[largest]) + largest = l; + + // If right child is larger than largest so far + if (r < n && arr[r] > arr[largest]) + largest = r; + + // If largest is not root + if (largest != i) + { + swap(arr[i], arr[largest]); + + // Recursively heapify the affected sub-tree + heapify(arr, n, largest); + } +} + +// main function to do heap sort +void heapSort(int arr[], int n) +{ + // Build heap (rearrange array) + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + + // One by one extract an element from heap + for (int i=n-1; i>=0; i--) + { + // Move current root to end + swap(arr[0], arr[i]); + + // call max heapify on the reduced heap + heapify(arr, i, 0); + } +} + +/* A utility function to print array of size n */ +void printArray(int arr[], int n) +{ + for (int i=0; i 0); + Put (";"); + end loop; + end Put; + + procedure Swap (a : in out Integer; b : in out Integer) + is + c : constant Integer := a; + + + + begin + a := b; + b := c; + end Swap; + + function Sort (T : Vector) return Vector is + ----------------------- + -- Method prototype -- + ----------------------- + + function Merge (Left, Right : in out Vector) return Vector; + + ----------------------------- + -- Declaration of methods -- + ----------------------------- + + function Merge (Left, Right : in out Vector) return Vector is + Result : Vector; + begin + while not Is_Empty (Left) and not Is_Empty (Right) loop + if First_Element (Left) <= First_Element (Right) then + Append (Result, First_Element (Left)); + Left.Delete_First; + else + Append (Result, First_Element (Right)); + Right.Delete_First; + end if; + end loop; + + while not Is_Empty (Left) loop + Append (Result, First_Element (Left)); + Left.Delete_First; + end loop; + + while not Is_Empty (Right) loop + Append (Result, First_Element (Right)); + Right.Delete_First; + end loop; + + return Result; + end Merge; + + Left : Vector; + Right : Vector; + begin + if T.Length <= Ada.Containers.Count_Type (1) then + return T; + end if; + + for i in First_Index (T) .. Last_Index (T) loop + if Ada.Containers.Count_Type (i) <= Ada.Containers.Count_Type (T.Length / +Ada.Containers.Count_Type (2)) then + Append (Left, T (i)); + else + Append (Right, T (i)); + end if; + end loop; + + Left := Sort (Left); + Right := Sort (Right); + + return Merge (Left, Right); + end Sort; + + --------------- + -- Variables -- + --------------- + + T : Vector := Init_Vector; +begin + Put ("Array : "); + Put (T); + New_Line; + + T := Sort (T); + + Put ("Sorted array : "); + Put (T); +end Merge_Sort; diff --git a/Sorting/Pancake sorting/pancake.java b/Sorting/Pancake sorting/pancake.java new file mode 100644 index 000000000..a008208e4 --- /dev/null +++ b/Sorting/Pancake sorting/pancake.java @@ -0,0 +1,89 @@ + +// Java program to +// sort array using +// pancake sort +import java.io.*; + +class PancakeSort { + + /* Reverses arr[0..i] */ + static void flip(int arr[], int i) + { + int temp, start = 0; + while (start < i) + { + temp = arr[start]; + arr[start] = arr[i]; + arr[i] = temp; + start++; + i--; + } + } + + // Returns index of the + // maximum element in + // arr[0..n-1] + static int findMax(int arr[], int n) + { + int mi, i; + for (mi = 0, i = 0; i < n; ++i) + if (arr[i] > arr[mi]) + mi = i; + return mi; + } + + // The main function that + // sorts given array using + // flip operations + static int pancakeSort(int arr[], int n) + { + // Start from the complete + // array and one by one + // reduce current size by one + for (int curr_size = n; curr_size > 1; --curr_size) + { + // Find index of the + // maximum element in + // arr[0..curr_size-1] + int mi = findMax(arr, curr_size); + + // Move the maximum element + // to end of current array + // if it's not already at + // the end + if (mi != curr_size-1) + { + // To move at the end, + // first move maximum + // number to beginning + flip(arr, mi); + + // Now move the maximum + // number to end by + // reversing current array + flip(arr, curr_size-1); + } + } + return 0; + } + + /* Utility function to print array arr[] */ + static void printArray(int arr[], int arr_size) + { + for (int i = 0; i < arr_size; i++) + System.out.print(arr[i] + " "); + System.out.println(""); + } + + /* Driver function to check for above functions*/ + public static void main (String[] args) + { + int arr[] = {23, 10, 20, 11, 12, 6, 7}; + int n = arr.length; + + pancakeSort(arr, n); + + System.out.println("Sorted Array: "); + printArray(arr, n); + } +} \ No newline at end of file diff --git a/Sorting/Quicksort-3Partition/cpp/quicksort_3partition.cpp b/Sorting/Quicksort-3Partition/cpp/quicksort_3partition.cpp new file mode 100644 index 000000000..f82031404 --- /dev/null +++ b/Sorting/Quicksort-3Partition/cpp/quicksort_3partition.cpp @@ -0,0 +1,47 @@ +#include +#include + +using namespace std; + +vector partition3(vector &a, int l, int r) { + vector res(2); + int x = a[l]; + int i = l + 1; res[0] = l; res[1] = r; + while(i <= r && res[0] <= res[1]) { + if(a[i] < x) { + swap(a[res[0]], a[i]); + res[0]++; i++; + } + else if(a[i] > x) { + swap(a[res[1]], a[i]); + res[1]--; + } + else { + i++; + } + } + return res; +} + +void randomized_quick_sort(vector &a, int l, int r) { + if (l >= r) { + return; + } + int k = l + rand() % (r - l + 1); + swap(a[l], a[k]); + vector res = partition3(a, l, r); + randomized_quick_sort(a, l, res[0] - 1); + randomized_quick_sort(a, res[1] + 1, r); +} + +int main() { + int n; cin >> n; + vector a(n); + for (int i = 0; i < a.size(); ++i) { + cin >> a[i]; + } + randomized_quick_sort(a, 0, a.size() - 1); + for (int i = 0; i < a.size(); ++i) { + cout << a[i] << ' '; + } +} diff --git a/Sorting/Quicksort-3Partition/python/quicksort_3partition.py b/Sorting/Quicksort-3Partition/python/quicksort_3partition.py new file mode 100644 index 000000000..fe363ace6 --- /dev/null +++ b/Sorting/Quicksort-3Partition/python/quicksort_3partition.py @@ -0,0 +1,34 @@ +import random + +def partition3(a, l, r): + x = a[l] + i = l + 1 + lt = l + gt = r + while i <= r and lt <= gt: + if a[i] < x: + a[lt], a[i] = a[i], a[lt] + lt += 1 + i += 1 + elif a[i] > x: + a[gt], a[i] = a[i], a[gt] + gt -= 1 + else: + i += 1 + return lt, gt + +def randomized_quick_sort(a, l, r): + if l >= r: + return + k = random.randint(l, r) + a[l], a[k] = a[k], a[l] + lt, gt = partition3(a, l, r) + randomized_quick_sort(a, l, lt - 1); + randomized_quick_sort(a, gt + 1, r); + +if __name__ == '__main__': + n = int(input()) + a = [int(x) for x in input().split()] + randomized_quick_sort(a, 0, n - 1) + for x in a: + print(x, end=' ') diff --git a/Sorting/Selection Sort/selection_sort.c b/Sorting/Selection Sort/selection_sort.c new file mode 100644 index 000000000..8c9d7f830 --- /dev/null +++ b/Sorting/Selection Sort/selection_sort.c @@ -0,0 +1,44 @@ +/* Selection Sort implementation in C; + * Author : Felipe Gabriel; + * Input : Array lenght and elements; + * Output : Sorted array elements; +*/ + +#include + +void selection_sort(int size, int *v){ + int i, j, min, aux; + for (i = 0; i < (size-1); i++){ + min = i; + for (j = (i+1); j < size; j++) { + if(v[j] < v[min]){ + min = j; + } + } + if (v[i] != v[min]) { + aux = v[i]; + v[i] = v[min]; + v[min] = aux; + } + } +} + +int main(){ + int size,j; + scanf("%d",&size); + int v[size]; + + for(j = 0; j < size; j++){ + scanf("%d",&v[j]); + } + selection_sort(size,v); + for(j = 0; j < size; j++){ + if(j != size-1){ + printf("%d ",v[j]); + } + else{ + printf("%d\n",v[j]); + } + } + return 0; +} \ No newline at end of file diff --git a/Sorting/Topological Sort/C/topological_sort.c b/Sorting/Topological Sort/C/topological_sort.c new file mode 100644 index 000000000..f6dc30e32 --- /dev/null +++ b/Sorting/Topological Sort/C/topological_sort.c @@ -0,0 +1,89 @@ +#include "stdio.h" +#include "stdlib.h" +#include "string.h" + +struct node +{ + int data; + struct node* next; +}; + +struct Time +{ + int disc; + int fsh; +}; + +void addedge(struct node* a[],int u,int v){ + struct node* temp=(struct node*)malloc(sizeof(struct node)); + temp->data=v; + temp->next=a[u]; + a[u]=temp; +} + +void DFS_visit(struct node* a[],struct Time tm[],int u,int t,int color[],struct node** topo){ + t=t+1; + tm[u].disc=t; + color[u]=1; + struct node* v=a[u]; + while(v!=NULL){ + if (color[v->data]==0) + { + DFS_visit(a,tm,v->data,t,color,topo); + } + v=v->next; + } + color[u]=-1; + t++; + tm[u].fsh=t; + struct node* temp=(struct node*)malloc(sizeof(struct node)); + temp->data=u; + temp->next=*topo; + *topo=temp; +} + +void DFS(struct node* a[],struct Time tm[],struct node** topo){ + int color[10]; + for (int i = 0; i <10; ++i) + { + color[i]=0; + } + int t=0; + for (int i = 0; i < 10; ++i) + { + if (color[i]==0 && a[i]!=NULL) + { + DFS_visit(a,tm,i,t,color,topo); + } + } +} + +void TS(struct node* a[],struct Time t[]){ + struct node* topo=NULL; + DFS(a,t,&topo); + struct node* temp=topo; + while(temp!=NULL){ + printf("%d ",temp->data); + temp=temp->next; + } + printf("\n"); +} + +int main() +{ + struct node* a[10]; + struct Time t[10]; + for (int i = 0; i < 10; ++i) + { + a[i]=NULL; + } + addedge(a,0,1); + addedge(a,0,3); + addedge(a,1,4); + addedge(a,4,3); + addedge(a,2,4); + addedge(a,2,5); + addedge(a,4,6); + TS(a,t); + return 0; +} \ No newline at end of file diff --git a/Sorting/bubbleSort/bubble.c b/Sorting/bubbleSort/bubble.c new file mode 100644 index 000000000..c76258427 --- /dev/null +++ b/Sorting/bubbleSort/bubble.c @@ -0,0 +1,46 @@ +/* Bubble Sort implementation in C; + * Author : Felipe Gabriel; + * Input : Array lenght and elements; + * Output : Sorted array elements; +*/ + +#include + +int n; + +void bubble_sort(int v[]){ + int i,k,aux = 0; + for(i = 0; i < n; i++){ + for(k = 0; k < n-1; k++){ + if(v[k] > v[k+1]){ + aux = v[k+1]; + v[k+1] = v[k]; + v[k] = aux; + } + } + } + +} + + +int main(){ + int j; + scanf("%d",&n); + int v[n]; + + for(j = 0; j < n; j++){ + scanf("%d",&v[j]); + } + bubble_sort(v); + for(j = 0; j < n; j++){ + if(j != n-1){ + printf("%d ",v[j]); + } + + else{ + printf("%d\n",v[j]); + } + } + + return 0; +} diff --git a/Sorting/bucketsort.cpp b/Sorting/bucketsort.cpp new file mode 100644 index 000000000..a53127acb --- /dev/null +++ b/Sorting/bucketsort.cpp @@ -0,0 +1,41 @@ +#include +#include +#include + +using namespace std; + + +void bucketSort(float a[], int n) +{ + vector t[n]; + + for (int i=0; i +#include +#define RANGE 255 + +// The main function that sort the given string arr[] in +// alphabatical order +void countSort(char arr[]) +{ + // The output character array that will have sorted arr + char output[strlen(arr)]; + + // Create a count array to store count of inidividul + // characters and initialize count array as 0 + int count[RANGE + 1], i; + memset(count, 0, sizeof(count)); + + // Store count of each character + for(i = 0; arr[i]; ++i) + ++count[arr[i]]; + + // Change count[i] so that count[i] now contains actual + // position of this character in output array + for (i = 1; i <= RANGE; ++i) + count[i] += count[i-1]; + + // Build the output character array + for (i = 0; arr[i]; ++i) + { + output[count[arr[i]]-1] = arr[i]; + --count[arr[i]]; + } + + // Copy the output array to arr, so that arr now + // contains sorted characters + for (i = 0; arr[i]; ++i) + arr[i] = output[i]; +} + +// Driver program to test above function +int main() +{ + char arr[] = "Hi there!";//"applepp"; + + countSort(arr); + + printf("Sorted character array is %sn", arr); + return 0; +} diff --git a/Sorting/insertionSort/Ruby/insertion_sort.rb b/Sorting/insertionSort/Ruby/insertion_sort.rb new file mode 100644 index 000000000..e9a89f4a9 --- /dev/null +++ b/Sorting/insertionSort/Ruby/insertion_sort.rb @@ -0,0 +1,23 @@ +def insertion_sort(array) + for i in 1..(array.length-1) + key = array[i] + j = i-1 + while j >= 0 and key < array[j] + array[j+1] = array[j] + j = j - 1 + end + array[j+1] = key + end +end + + +# Dummy data for testing +test_array = [7, 6, 5, 4, 3, 2, 1] +# Display unsorted array +puts "Unsorted Array:" +puts test_array.join(' ') +# Perform insertion sorting +insertion_sort(test_array) +# Display the sorted results +puts "Post Insertion Sort" +puts test_array.join(' ') diff --git a/Sorting/quickSort/Ruby/quick_sort.rb b/Sorting/quickSort/Ruby/quick_sort.rb new file mode 100644 index 000000000..b9de5c087 --- /dev/null +++ b/Sorting/quickSort/Ruby/quick_sort.rb @@ -0,0 +1,33 @@ +def partition(array, low, high) + pivot = array[high] # Selecting the last element of the array as the pivot element + + idx = low - 1 # Rightful index of the pivot element + + for counter in low..high + if array[counter] < pivot + idx = idx + 1 + array[counter], array[idx] = array[idx], array[counter] + end + end + array[idx+1], array[high] = array[high], array[idx+1] + return idx + 1 +end + +def quick_sort(array, low, high) + if low < high + idx = partition(array, low, high) # The partition index + quick_sort(array, low, idx-1) + quick_sort(array, idx+1, high) + end +end + +# Dummy data for testing +test_array = [7, 6, 5, 4, 3, 2, 1] +# Display unsorted array +puts "Unsorted Array:" +puts test_array.join(' ') +# Perform quick sort +quick_sort(test_array, 0, 6) +# Display the sorted results +puts "Post QuickSort" +puts test_array.join(' ') diff --git a/Sorting/quickSort/python/quicksort.py b/Sorting/quickSort/python/quicksort.py new file mode 100644 index 000000000..5ad064db6 --- /dev/null +++ b/Sorting/quickSort/python/quicksort.py @@ -0,0 +1,28 @@ +import random + +def partition2(a, l, r): + x = a[l] + j = l; + for i in range(l + 1, r + 1): + if a[i] <= x: + j += 1 + a[i], a[j] = a[j], a[i] + a[l], a[j] = a[j], a[l] + return j + +def randomized_quick_sort(a, l, r): + if l >= r: + return + k = random.randint(l, r) + a[l], a[k] = a[k], a[l] + m = partition2(a, l, r) + randomized_quick_sort(a, l, m - 1); + randomized_quick_sort(a, m + 1, r); + + +if __name__ == '__main__': + n = int(input()) + a = [int(x) for x in input().split()] + randomized_quick_sort(a, 0, n - 1) + for x in a: + print(x, end=' ') diff --git a/Tree/AVLTree/AVL.cpp b/Tree/AVLTree/AVL.cpp new file mode 100644 index 000000000..802eada4b --- /dev/null +++ b/Tree/AVLTree/AVL.cpp @@ -0,0 +1,358 @@ +// +// Created by insane-abhi on 23/9/18. +// + +#include "AVL.hpp" +#include +using namespace std; + +inline int max(int a, int b) { + return (a>b)? a: b; +} + +template +int height(AVLnode* N) { + if(N== nullptr) + return 0; + return N->height; +} + +template +AVLnode* newNode(Key key, Value value) { + AVLnode* node = (AVLnode*)malloc(sizeof(AVLnode)); + node->key = key; + node->val = value; + node->left = nullptr; + node->right = nullptr; + node->height = 1; + return node; +} + +template +AVLnode* rightRotate(AVLnode *y) { + AVLnode *x = y->left; + AVLnode *T2 = x->right; + x->right = y; + y->left = T2; + y->height = max(height(y->left),height(y->right))+1; + x->height = max(height(x->left),height(x->right))+1; + return x; +} + +template +AVLnode* leftRotate(AVLnode *x) { + AVLnode *y = x->right; + AVLnode *T2 = y->left; + y->left = x; + x->right = T2; + x->height = max(height(x->left),height(x->right))+1; + y->height = max(height(y->left),height(y->right))+1; + return y; +} + +template +int getBalance(AVLnode* N) { + if(N== nullptr) + return 0; + return height(N->left)-height(N->right); +} + +template +AVLnode* insert(AVLnode* node, Key key, Value value) { + if(node== nullptr) + return newNode(key,value); + if (key <= node->key) + node->left = insert(node->left,key,value); + else if(key > node->key) + node->right = insert(node->right,key,value); + else + return node; + + node->height = 1 + max(height(node->left),height(node->right)); + int balance = getBalance(node); + + if(balance>1 && keyleft->key) + return rightRotate(node); + if(balance<-1 && key>node->right->key) + return leftRotate(node); + if(balance>1 && key>node->left->key) { + node->left = leftRotate(node->left); + return rightRotate(node); + } + if(balance<-1 && key < node->right->key) { + node->right = rightRotate(node->right); + return leftRotate(node); + } + return node; +} + +template +AVLnode* minValueNode(AVLnode* node) { + AVLnode* current = node; + while (current->left!= nullptr) + current = current->left; + return current; +} + +template +AVLnode* deleteNode(AVLnode* root, Key key) { + if(root== nullptr) + return root; + if(keykey) + root->left = deleteNode(root->left,key); + else if (key>root->key) + root->right = deleteNode(root->right,key); + else { + if((root->left == nullptr) || (root->right== nullptr)) { + AVLnode* temp = root->left?root->left:root->right; + if(temp== nullptr) { + temp = root; + root = nullptr; + } + else + *root = *temp; + free(temp); + } + else { + AVLnode *temp = minValueNode(root->right); + root->key = temp->key; + root->right = deleteNode(root->right, temp->key); + } + } + + if (root == nullptr) + return root; + + root->height = 1+max(height(root->left),height(root->right)); + int balance = getBalance(root); + if (balance>1 && getBalance(root->left) >=0) + return rightRotate(root); + if(balance>1 && getBalance(root->left) < 0) { + root->left = leftRotate(root->left); + return rightRotate(root); + } + if(balance<-1 && getBalance(root->right) <= 0) + return leftRotate(root); + if(balance<-1 && getBalance(root->right) > 0) { + root->right = rightRotate(root->right); + return leftRotate(root); + } + return root; +} +template +void preOrder(AVLnode *root) { + if(root!= nullptr) { + cout << root->key << " " << root->val << endl; + preOrder(root->left); + preOrder(root->right); + } +} +template +AVLnode* Find(Key key, AVLnode* node) { + if (node->key == key) + return node; + else if (node->key > key) { + if (node->left != nullptr) + return Find(key, node->left); + return node; + } else if (node->key < key) { + if (node->right != nullptr) + return Find(key, node->right); + return node; + } +} +template +void inOrder(AVLnode* node) { + if(node== nullptr) + return; + else { + inOrder(node->left); + cout << node->key << " " << node->val << endl; + inOrder(node->right); + } +} +template +void postOrder(AVLnode* node) { + if(node== nullptr) + return; + else { + postOrder(node->left); + postOrder(node->right); + cout << node->key << " " << node->val << endl; + } +} +template +AVLnode* maxValueNode(AVLnode* node) { + AVLnode* current = node; + while (current->right!= nullptr) + current = current->right; + return current; +} +template +void inOrderPredecesor(AVLnode* root, AVLnode*& pre, Key key) { + if(root== nullptr) return; + if(root->key==key) { + if(root->left!= nullptr) { + pre = maxValueNode(root->left); + } + } + else if(root->key > key) { + inOrderPredecesor(root->left,pre,key); + } + else { + pre = root; + inOrderPredecesor(root->right,pre,key); + } +} +template +void inOrderSuccessor(AVLnode* root, AVLnode*& suc, Key key) { + if(root== nullptr) return; + + if (root->key == key) { + if(root->right!= nullptr) { + AVLnode* tmp = root->right; + while(tmp->left) + tmp = tmp->left; + suc = tmp; + } + } + + else if(root->key > key) { + suc = root; + inOrderSuccessor(root->left,suc,key); + } + else { + inOrderSuccessor(root->right,suc,key); + } +} +template +int count(AVLnode* n) { + int c = 1; + if(n== nullptr) + return 0; + else { + c += count(n->left); + c += count(n->right); + return c; + } +} +template +void AVL::put(const Key &key, const Value &value) { + AVLnode* current = root; + current = insert(current,key,value); + root = current; +} +template +void AVL::print_pre_order() { + AVLnode* current = root; + preOrder(current); + cout << endl; +} +template +void AVL::remove(const Key &key) { + root = deleteNode(root,key); +} +template +Value AVL::get(const Key &key) { + AVLnode* current = root; + return Find(key,current)->val; +} +template +bool AVL::has(const Key &key) { + AVLnode* current=root; + if(Find(key,current)->key==key) + return true; + else + return false; +} +template +Key AVL::successor(const Key &key) { + AVLnode* current = root; + AVLnode* suc = nullptr; + inOrderSuccessor(current,suc,key); + return suc->key; +} +template +Key AVL::predecessor(const Key &key) { + AVLnode* current = root; + AVLnode* pre = nullptr; + inOrderPredecesor(current,pre,key); + return pre->key; +} +template +Key AVL::minimum() { + return minValueNode(root)->key; +} +template +Key AVL::maximum() { + return maxValueNode(root)->key; +} +template +void AVL::print_in_order() { + inOrder(root); +} +template +void AVL::print_post_order() { + postOrder(root); +} +template +int AVL::getHeight() { + return root->height; +} +template +void AVL::print() { + inOrder(root); +} +template +int AVL::size() { + return count(root); +} +template +void q1(AVLnode* root, Key k1, Key k2, Value val, Value& count) { + if(root == nullptr) + return; + if(k1 < root->key) + q1(root->left,k1,k2,val,count); + if(k1 < root->key && k2 >= root->key) { + if(abs(root->val-val)val-val); + } + + if(k2 > root->key) + q1(root->right,k1,k2,val,count); +} +template +Value AVL::que_1(Key &key, Value &val) { + Value count = INT32_MAX; + AVLnode* current = root; + Key max = maximum(); + q1(current,key,max,val,count); + if(count == INT32_MAX) + return -1; + else + return count; +} +template +void q2(AVLnode* root, Key k1, Key k2, Value val, Value& count) { + if(root == nullptr) + return; + if(k1 < root->key) + q2(root->left,k1,k2,val,count); + if(k1 <= root->key && k2 > root->key) { +// cout << root->key << " " << root->val << " "; + if(root->val>val) { + count++; + } + } + + if(k2 > root->key) + q2(root->right,k1,k2,val,count); +} +template +Value AVL::que_2(Key &key, Value &val) { + Value count = 0; + AVLnode *current = root; + Key min = minimum(); + q2(current,min,key,val,count); + return count; +} \ No newline at end of file diff --git a/Tree/AVLTree/AVL.hpp b/Tree/AVLTree/AVL.hpp new file mode 100644 index 000000000..981cc9e99 --- /dev/null +++ b/Tree/AVLTree/AVL.hpp @@ -0,0 +1,42 @@ +//created by insane-abhi +#ifndef AVL_HPP +#define AVL_HPP 1 +template +class AVLnode +{ +public: + Key key; + Value val; + AVLnode * left,* right; + int height; + /*Default constructor. Should assign the default value to key and value + */ + AVLnode(); + /*This contructor should assign the key and val from the passed parameters + */ + AVLnode(Key key, Value value); +}; +template +class AVL { +protected: + AVLnode* root = nullptr; +public: + virtual void put(const Key& key, const Value& value); + virtual void remove(const Key& key); + virtual void print_pre_order(); + virtual Value get(const Key& key); + virtual bool has(const Key& key); + virtual void print_in_order(); + virtual void print_post_order(); + virtual Key minimum(); + virtual Key maximum(); + virtual Key successor(const Key& key); + virtual Key predecessor(const Key& key); + virtual int getHeight(); + virtual int size(); + virtual void print(); + Value que_1(Key& key, Value& val); + Value que_2(Key& key, Value& val); +}; + +#endif /* ifndef AVL_HPP */ \ No newline at end of file diff --git a/Tree/AVLTree/AVL_Tree.cpp b/Tree/AVLTree/AVL_Tree.cpp new file mode 100644 index 000000000..5cea1f113 --- /dev/null +++ b/Tree/AVLTree/AVL_Tree.cpp @@ -0,0 +1,354 @@ +#include "AVL.hpp" +#include +using namespace std; + +inline int max(int a, int b) { + return (a>b)? a: b; +} + +template +int height(AVLnode* N) { + if(N== nullptr) + return 0; + return N->height; +} + +template +AVLnode* newNode(Key key, Value value) { + AVLnode* node = (AVLnode*)malloc(sizeof(AVLnode)); + node->key = key; + node->val = value; + node->left = nullptr; + node->right = nullptr; + node->height = 1; + return node; +} + +template +AVLnode* rightRotate(AVLnode *y) { + AVLnode *x = y->left; + AVLnode *T2 = x->right; + x->right = y; + y->left = T2; + y->height = max(height(y->left),height(y->right))+1; + x->height = max(height(x->left),height(x->right))+1; + return x; +} + +template +AVLnode* leftRotate(AVLnode *x) { + AVLnode *y = x->right; + AVLnode *T2 = y->left; + y->left = x; + x->right = T2; + x->height = max(height(x->left),height(x->right))+1; + y->height = max(height(y->left),height(y->right))+1; + return y; +} + +template +int getBalance(AVLnode* N) { + if(N== nullptr) + return 0; + return height(N->left)-height(N->right); +} + +template +AVLnode* insert(AVLnode* node, Key key, Value value) { + if(node== nullptr) + return newNode(key,value); + if (key <= node->key) + node->left = insert(node->left,key,value); + else if(key > node->key) + node->right = insert(node->right,key,value); + else + return node; + + node->height = 1 + max(height(node->left),height(node->right)); + int balance = getBalance(node); + + if(balance>1 && keyleft->key) + return rightRotate(node); + if(balance<-1 && key>node->right->key) + return leftRotate(node); + if(balance>1 && key>node->left->key) { + node->left = leftRotate(node->left); + return rightRotate(node); + } + if(balance<-1 && key < node->right->key) { + node->right = rightRotate(node->right); + return leftRotate(node); + } + return node; +} + +template +AVLnode* minValueNode(AVLnode* node) { + AVLnode* current = node; + while (current->left!= nullptr) + current = current->left; + return current; +} + +template +AVLnode* deleteNode(AVLnode* root, Key key) { + if(root== nullptr) + return root; + if(keykey) + root->left = deleteNode(root->left,key); + else if (key>root->key) + root->right = deleteNode(root->right,key); + else { + if((root->left == nullptr) || (root->right== nullptr)) { + AVLnode* temp = root->left?root->left:root->right; + if(temp== nullptr) { + temp = root; + root = nullptr; + } + else + *root = *temp; + free(temp); + } + else { + AVLnode *temp = minValueNode(root->right); + root->key = temp->key; + root->right = deleteNode(root->right, temp->key); + } + } + + if (root == nullptr) + return root; + + root->height = 1+max(height(root->left),height(root->right)); + int balance = getBalance(root); + if (balance>1 && getBalance(root->left) >=0) + return rightRotate(root); + if(balance>1 && getBalance(root->left) < 0) { + root->left = leftRotate(root->left); + return rightRotate(root); + } + if(balance<-1 && getBalance(root->right) <= 0) + return leftRotate(root); + if(balance<-1 && getBalance(root->right) > 0) { + root->right = rightRotate(root->right); + return leftRotate(root); + } + return root; +} +template +void preOrder(AVLnode *root) { + if(root!= nullptr) { + cout << root->key << " " << root->val << endl; + preOrder(root->left); + preOrder(root->right); + } +} +template +AVLnode* Find(Key key, AVLnode* node) { + if (node->key == key) + return node; + else if (node->key > key) { + if (node->left != nullptr) + return Find(key, node->left); + return node; + } else if (node->key < key) { + if (node->right != nullptr) + return Find(key, node->right); + return node; + } +} +template +void inOrder(AVLnode* node) { + if(node== nullptr) + return; + else { + inOrder(node->left); + cout << node->key << " " << node->val << endl; + inOrder(node->right); + } +} +template +void postOrder(AVLnode* node) { + if(node== nullptr) + return; + else { + postOrder(node->left); + postOrder(node->right); + cout << node->key << " " << node->val << endl; + } +} +template +AVLnode* maxValueNode(AVLnode* node) { + AVLnode* current = node; + while (current->right!= nullptr) + current = current->right; + return current; +} +template +void inOrderPredecesor(AVLnode* root, AVLnode*& pre, Key key) { + if(root== nullptr) return; + if(root->key==key) { + if(root->left!= nullptr) { + pre = maxValueNode(root->left); + } + } + else if(root->key > key) { + inOrderPredecesor(root->left,pre,key); + } + else { + pre = root; + inOrderPredecesor(root->right,pre,key); + } +} +template +void inOrderSuccessor(AVLnode* root, AVLnode*& suc, Key key) { + if(root== nullptr) return; + + if (root->key == key) { + if(root->right!= nullptr) { + AVLnode* tmp = root->right; + while(tmp->left) + tmp = tmp->left; + suc = tmp; + } + } + + else if(root->key > key) { + suc = root; + inOrderSuccessor(root->left,suc,key); + } + else { + inOrderSuccessor(root->right,suc,key); + } +} +template +int count(AVLnode* n) { + int c = 1; + if(n== nullptr) + return 0; + else { + c += count(n->left); + c += count(n->right); + return c; + } +} +template +void AVL::put(const Key &key, const Value &value) { + AVLnode* current = root; + current = insert(current,key,value); + root = current; +} +template +void AVL::print_pre_order() { + AVLnode* current = root; + preOrder(current); + cout << endl; +} +template +void AVL::remove(const Key &key) { + root = deleteNode(root,key); +} +template +Value AVL::get(const Key &key) { + AVLnode* current = root; + return Find(key,current)->val; +} +template +bool AVL::has(const Key &key) { + AVLnode* current=root; + if(Find(key,current)->key==key) + return true; + else + return false; +} +template +Key AVL::successor(const Key &key) { + AVLnode* current = root; + AVLnode* suc = nullptr; + inOrderSuccessor(current,suc,key); + return suc->key; +} +template +Key AVL::predecessor(const Key &key) { + AVLnode* current = root; + AVLnode* pre = nullptr; + inOrderPredecesor(current,pre,key); + return pre->key; +} +template +Key AVL::minimum() { + return minValueNode(root)->key; +} +template +Key AVL::maximum() { + return maxValueNode(root)->key; +} +template +void AVL::print_in_order() { + inOrder(root); +} +template +void AVL::print_post_order() { + postOrder(root); +} +template +int AVL::getHeight() { + return root->height; +} +template +void AVL::print() { + inOrder(root); +} +template +int AVL::size() { + return count(root); +} +template +void q1(AVLnode* root, Key k1, Key k2, Value val, Value& count) { + if(root == nullptr) + return; + if(k1 < root->key) + q1(root->left,k1,k2,val,count); + if(k1 < root->key && k2 >= root->key) { + if(abs(root->val-val)val-val); + } + + if(k2 > root->key) + q1(root->right,k1,k2,val,count); +} +template +Value AVL::que_1(Key &key, Value &val) { + Value count = INT32_MAX; + AVLnode* current = root; + Key max = maximum(); + q1(current,key,max,val,count); + if(count == INT32_MAX) + return -1; + else + return count; +} +template +void q2(AVLnode* root, Key k1, Key k2, Value val, Value& count) { + if(root == nullptr) + return; + if(k1 < root->key) + q2(root->left,k1,k2,val,count); + if(k1 <= root->key && k2 > root->key) { +// cout << root->key << " " << root->val << " "; + if(root->val>val) { + count++; + } + } + + if(k2 > root->key) + q2(root->right,k1,k2,val,count); +} +template +Value AVL::que_2(Key &key, Value &val) { + Value count = 0; + AVLnode *current = root; + Key min = minimum(); + q2(current,min,key,val,count); + return count; +} diff --git a/Tree/AVLTree/main.cpp b/Tree/AVLTree/main.cpp new file mode 100644 index 000000000..e80d4a9a0 --- /dev/null +++ b/Tree/AVLTree/main.cpp @@ -0,0 +1,44 @@ +//created by insane-abhi +//driver function +//sample code for testing AVL +#include +#include "AVL.cpp" + +using namespace std; +int main() { + int roll_no; + string name; + AVL students; //int represents key datatype and string represents value datatype + cout << "Enter no. of entries: "; + int n; + cin >> n; + cout << endl; + for(int i=1; i<=n; i++) { + cout << "Enter roll no: "; + cin >> roll_no; + cout << endl; + cout << "Enter name: "; + cin >> name; + cout << endl; + students.put(roll_no,name); + } + cout << "Search for a roll_no | Enter the roll.no: "; + cin >> roll_no; + cout << endl; + cout << students.has(roll_no) << " (1 if present else 0)" << endl; + cout << "Find name associated with a rollNo | Enter roll_no: "; + cin >> roll_no; + cout << students.get(roll_no) << endl; + cout << "Remove a particular roll no. | Enter Roll no: "; + cin >> roll_no; + students.remove(roll_no); + cout << "Printing the directory: " << endl; + students.print_in_order(); + cout << "Printing Max and Min roll No. " << endl; + cout << "Max: " << students.maximum() << " Min: " << students.minimum() << endl << "Enter no. for predecessor" << endl; + cin >> roll_no; + cout << students.predecessor(roll_no) << endl; + cout << "Height of Tree: " << students.getHeight() << endl; + cout << "No. Of Nodes: " << students.size() << endl; + return 0; +} \ No newline at end of file diff --git a/Tree/Binary Search Tree/SumOfKSmallestElements.cpp b/Tree/Binary Search Tree/SumOfKSmallestElements.cpp new file mode 100644 index 000000000..d5c63a452 --- /dev/null +++ b/Tree/Binary Search Tree/SumOfKSmallestElements.cpp @@ -0,0 +1,78 @@ +// Sum of k smallest elements in BST + +#include +using namespace std; + +struct Node +{ + int data; + Node* left, * right; +}; + +struct Node *createNode(int data) +{ + Node * new_Node = new Node; + new_Node->left = NULL; + new_Node->right = NULL; + new_Node->data = data; + return new_Node; +} + +struct Node * insert(Node *root, int key) +{ + if (root == NULL) + return createNode(key); + + if (root->data > key) + root->left = insert(root->left, key); + + else if (root->data < key) + root->right = insert(root->right, key); + + return root; +} + +int ksmallestElementSumRec(Node *root, int k, int &count) +{ + if (root == NULL) + return 0; + if (count > k) + return 0; + + int res = ksmallestElementSumRec(root->left, k, count); + if (count >= k) + return res; + + res += root->data; + + count++; + if (count >= k) + return res; + return res + ksmallestElementSumRec(root->right, k, count); +} + +int ksmallestElementSum(struct Node *root, int k) +{ + int count = 0; + ksmallestElementSumRec(root, k, count); +} + +int main() +{ + int n,ele,k; + Node *root = NULL; + printf("Enter No of nodes\n"); + scanf("%d",&n); + int i=0; + while(i +#include + +struct btnode +{ + int value; + struct btnode *l; + struct btnode *r; +}*root = NULL, *temp = NULL, *t2, *t1; + + +void insert(); +void inorder(struct btnode *t); +void create(); +void search(struct btnode *t); +void preorder(struct btnode *t); +void postorder(struct btnode *t); + + +int flag = 1; + +int main() +{ + int ch; + + printf("\nOPERATIONS ---"); + printf("\n1 - Insert an element into tree\n"); + printf("2 - Inorder Traversal\n"); + printf("3 - Preorder Traversal\n"); + printf("4 - Postorder Traversal\n"); + printf("5 - Exit\n"); + while(1) + { + printf("\nEnter your choice : "); + scanf("%d", &ch); + switch (ch) + { + case 1: + insert(); + break; + case 2: + inorder(root); + break; + case 3: + preorder(root); + break; + case 4: + postorder(root); + break; + case 5: + exit(0); + default : + printf("Wrong choice, Please enter correct choice "); + break; + } + } + return 0; +} + +/* To insert a node in the tree */ +void insert() +{ + create(); + if (root == NULL) + root = temp; + else + search(root); +} + +/* To create a node */ +void create() +{ + int data; + + printf("Enter data of node to be inserted : "); + scanf("%d", &data); + temp = (struct btnode *)malloc(1*sizeof(struct btnode)); + temp->value = data; + temp->l = temp->r = NULL; +} + +/* Function to search the appropriate position to insert the new node */ +void search(struct btnode *t) +{ + if ((temp->value > t->value) && (t->r != NULL)) /* value more than root node value insert at right */ + search(t->r); + else if ((temp->value > t->value) && (t->r == NULL)) + t->r = temp; + else if ((temp->value < t->value) && (t->l != NULL)) /* value less than root node value insert at left */ + search(t->l); + else if ((temp->value < t->value) && (t->l == NULL)) + t->l = temp; +} + +/* recursive function to perform inorder traversal of tree */ +void inorder(struct btnode *t) +{ + if (root == NULL) + { + printf("No elements in a tree to display"); + return; + } + if (t->l != NULL) + inorder(t->l); + printf("%d -> ", t->value); + if (t->r != NULL) + inorder(t->r); +} + + +/* To find the preorder traversal */ +void preorder(struct btnode *t) +{ + if (root == NULL) + { + printf("No elements in a tree to display"); + return; + } + printf("%d -> ", t->value); + if (t->l != NULL) + preorder(t->l); + if (t->r != NULL) + preorder(t->r); +} + +/* To find the postorder traversal */ +void postorder(struct btnode *t) +{ + if (root == NULL) + { + printf("No elements in a tree to display "); + return; + } + if (t->l != NULL) + postorder(t->l); + if (t->r != NULL) + postorder(t->r); + printf("%d -> ", t->value); +} diff --git a/Tree/Binary Tree to Linked List/cpp/BinaryTreeToLinkedList.cpp b/Tree/Binary Tree to Linked List/cpp/BinaryTreeToLinkedList.cpp new file mode 100644 index 000000000..7289021ca --- /dev/null +++ b/Tree/Binary Tree to Linked List/cpp/BinaryTreeToLinkedList.cpp @@ -0,0 +1,122 @@ +#include + +using namespace std; + +class Node{ + public: + Node* left; + Node* right; + int data; + Node(int x){ + data = x; + left = NULL; + right = NULL; + } +}; + +class Solution{ + public: + Node* insert(Node* root, int data) { + if(root == NULL) { + return new Node(data); + } else { + Node* cur; + if(data <= root->data) { + cur = insert(root->left, data); + root->left = cur; + } else { + cur = insert(root->right, data); + root->right = cur; + } + + return root; + } + } + + Node* flatten(Node* A) { + if(!A)return NULL; + + // Take the left and right subtree + Node* tempr = A->right; + Node* templ = A->left; + + // Recursively Flatten them + flatten(templ); + flatten(tempr); + + // If left subtree exists, place it as the right subtree and make the right subtree + // as the child of this new right subtree + if(templ){ + A->right = templ; + Node* x = templ; + // Go to the end of the right subtree (which was earlier left subtree) + while(x->right){ + x = x->right; + } + // Place the earlier right subtree as the right subtree of the current right subtree + x->right = tempr; + + // Make the new left subtree as NULL + templ->left = NULL; + } + + // Nullify the left subtree. + A->left = NULL; + + // Return the tree. + return A; + } + + void inOrder(Node* tree){ + if(!tree) return; + + inOrder(tree->left); + cout << tree->data << " " ; + inOrder(tree->right); + } +}; + +// Initial Tree: +// 4 +// / \ +// 2 7 +// / \ / +// 1 3 6 + +// Final Tree: +// 4 +// / \ +// N 2 +// / \ +// N 1 +// / \ +// N 3 +// / \ +// N 7 +// / \ +// N 6 +// N - NULL + + +int main() { + Solution myTree; + Node* root = NULL; + root = myTree.insert(root,4); + root = myTree.insert(root,2); + root = myTree.insert(root,3); + root = myTree.insert(root,1); + root = myTree.insert(root,7); + root = myTree.insert(root,6); + + cout << "InOrder Traversal is of the tree is as follows: " << endl; + myTree.inOrder(root); + cout << endl; + + + myTree.flatten(root); + cout << "\n\nInOrder Traversal is of the flattened tree is as follows: " << endl; + myTree.inOrder(root); + cout << endl; + return 0; +} + diff --git a/Tree/segment tree/c/segment_tree.c b/Tree/segment tree/c/segment_tree.c new file mode 100644 index 000000000..8a00e4fd7 --- /dev/null +++ b/Tree/segment tree/c/segment_tree.c @@ -0,0 +1,101 @@ +#include "stdio.h" +#include "math.h" +#include "limits.h" + +int min(int a,int b){ + return (a n || qi>qj) + { + printf("Invalid Input"); + return -1; + } + else{ + if (qi<=i && qj>=j) + { + return st[pos]; + } + if (jqj) + { + return INT_MAX; + } + int mid=i + (j -i)/2; + return min(range_min_query(st,n,i,mid,qi,qj,2*pos+1),range_min_query(st,n,mid+1,j,qi,qj,2*pos+2)); + } +} + +int main(int argc, char const *argv[]) +{ + int n; + printf("Enter the number of elements you want in an array: "); + scanf("%d",&n); + int a[n]; + printf("Enter elements of array: "); + for (int i = 0; i < n; ++i) + { + scanf("%d",&a[i]); + } + int h=ceil(log2(n)); + int max_size=2*pow(2,h)-1; + int st[max_size]; + build_ST(a,st,0,n-1,0); + + int bcd; + printf("Press 1 for Range Min query and 2 for update: "); + scanf("%d",&bcd); + if(bcd == 1){ + puts("\n"); + int qi,qj; + printf("Enter Range for which minimum has to be calculated: "); + scanf("%d %d",&qi,&qj); + int rmq=range_min_query(st,n,0,n-1,qi-1,qj-1,0); + printf("Minimum for this range: %d\n",rmq ); + puts(""); + } + + if(bcd==2){ + printf("Enter index to be updated"); + int idx; + scanf("%d",&idx); + printf("Enter value to be updated"); + int val; + scanf("%d",&val); + update(a,st,0,n-1,idx,val,0); + } + + + return 0; +} diff --git a/Tree/segment tree/golang/segmentTree.go b/Tree/segment tree/golang/segmentTree.go new file mode 100644 index 000000000..012be793c --- /dev/null +++ b/Tree/segment tree/golang/segmentTree.go @@ -0,0 +1,65 @@ +package main + +import "fmt" +import "math" + +var tree []int +var array []int + +func min(x, y int) int { + if x < y { + return x + } + return y +} + +func buildTree(node, start, end int) { + if start == end { + tree[node] = array[start] + return + } + mid := (start + end) / 2 + buildTree(2*node, start, mid) + buildTree(2*node+1, mid+1, end) + tree[node] = min(tree[2*node], tree[2*node+1]) +} + +func update(node, start, end, pos, value int) { + if start > pos || end < pos { + return + } + if start == end { + tree[node] = value + return + } + mid := (start + end) / 2 + update(2*node, start, mid, pos, value) + update(2*node+1, mid+1, end, pos, value) + tree[node] = min(tree[2*node], tree[2*node+1]) +} + +func query(node, start, end, i, j int) int { + if start >= i && end <= j { + return tree[node] + } + if start > j || end < i { + return math.MaxInt32 + } + mid := (start + end) / 2 + return min(query(2*node, start, mid, i, j), query(2*node+1, mid+1, end, i, j)) +} + +func main() { + array = []int{11, 2, 3, -1, 5, 0, 9, 7} + tree = make([]int, 2*len(array)) + buildTree(1, 0, len(array)-1) + + fmt.Printf("Min [11, 2, 3, -1, 5, 0, 9, 7] = %d\n", query(1, 0, len(array)-1, 0, 7)) + fmt.Printf("Min 11, 2, 3, -1, 5, [0, 9, 7] = %d\n", query(1, 0, len(array)-1, 5, 7)) + + update(1, 0, len(array)-1, 3, 4) + + fmt.Printf("Min [11, 2, 3, 4, 5, 0, 9, 7] = %d\n", query(1, 0, len(array)-1, 0, 7)) + fmt.Printf("Min [11, 2, 3, 4, 5], 0, 9, 7 = %d\n", query(1, 0, len(array)-1, 0, 4)) +} + diff --git a/data structures/Red Black/CPP/arvore_rb_c.cpp b/data structures/Red Black/CPP/arvore_rb_c.cpp new file mode 100644 index 000000000..0c0c717a4 --- /dev/null +++ b/data structures/Red Black/CPP/arvore_rb_c.cpp @@ -0,0 +1,393 @@ +#include "arvore_rb_c.h" + +/* +* Tree constructor: +* This implementation uses Sentinel nodes, so I create one, make his color black +* and then I make my root point to it. +*/ +Tree::Tree(){ + + this->T_NIL = criar_no(0,this->T_NIL); + this->T_NIL->color = BLACK; + this->root = this->T_NIL; + +} + +/* +* For the deconstructor I just remove all nodes from the memory. +*/ + +Tree::~Tree(){ + limpar(this->root, this->T_NIL); + + free(this->T_NIL); +} + +/* +* For the insertion in a RB, we just insert a RED node the same way we would in a Binary Search Tree. +* If the properties of the RB are violated, we have to fix it, that's why we call InsertFix. +*/ + +void Tree::insert(int x){ + + // If there's no nodes in the tree. I just insert at the root. + if(this->root == this->T_NIL){ + this->root = criar_no(x,this->T_NIL); + this->root->color = BLACK; + return; + } + + // Insertion like on an Binary Search Tree, saving the node's father. + node *tmp = this->root, *y; + while(tmp != this->T_NIL){ + y = tmp; + if(tmp->value > x){ + tmp = tmp->left; + } + else{ + tmp = tmp->right; + } + } + + tmp = criar_no(x, T_NIL); + tmp->p = y; + if(tmp->value < y->value) y->left = tmp; + else y->right = tmp; + tmp->right = tmp->left = T_NIL; + insertFix_RB(tmp); +} + + +// This function transforms node v into u. +void Tree::transplant(node* u, node *v){ + // If u is the root, v becomes the root. + if(u->p == T_NIL) this->root = v; + // If u is a left child, v becomes a left child. + else if(u == u->p->left) u->p->left = v; + // if u is a right child, v becomes a right child. + else u->p->right = v; + + // The father of v becomes u. + v->p = u->p; + // Then we delete node u. + free(u); +} + +/* +* This function deletes a node from the RB. +* The removal of a node is the same as a Binary Search Tree. +* If we delete a RED node, there's no need to fix the RB since no properties are violated. +* Else we call the function DeletionFix. +*/ + +void Tree::delet(node *z){ + node *y = z, *x; + + int yOriginalColor = y->color; + + // Deleting like a Binary Search Tree. + + // If there's no left child. + if(z->left == T_NIL){ + x = z->right; + transplant(z,z->right); + } + + // If there's no right child. + else if(z->right == T_NIL){ + x = z->left; + transplant(z, z->left); + } + + // If it has both childs. + else{ + y = minimum(y->right); + yOriginalColor = y->color; + x = y->right; + if(y->p == z) x->p = y; + else{ + transplant(y, y->right); + y->right = z->right; + y->right->p = y; + } + transplant(z,y); + y->left = z->left; + y->left->p = y; + y->color = z->color; + } + + if(yOriginalColor == BLACK) deleteFix_RB(x); +} + +/* +* Functions that rotates to the left or right around a node x. +*/ + +void Tree::rotacionar_esquerda(node *x){ + + node *y = x->right; + x->right = y->left; + + if(y->left != T_NIL){ + y->left->p = x; + } + + y->left = x; + + if(x->p == this->T_NIL) this->root = y; + else if(x->p->left == x) x->p->left = y; + else x->p->right = y; + + y->p = x->p; + x->p = y; +} + +void Tree::rotacionar_direita(node *x){ + + node *y = x->left; + x->left = y->right; + + if(y->right != T_NIL){ + y->right->p = x; + } + + y->right = x; + + if(x->p == this->T_NIL) this->root = y; + else if(x->p->left == x) x->p->left = y; + else x->p->right = y; + + y->p = x->p; + x->p = y; +} + +/* +* Function so search in a Binary Search Tree, returns the node found. +*/ + +node *Tree::search(int x){ + + node *tmp = this->root; + + while(tmp != T_NIL && tmp->value != x){ + + if(tmp->value > x){ + tmp = tmp->left; + } + + else if(tmp->value < x){ + tmp = tmp->right; + } + + } + return tmp; +} + +/* +* Finds the minimum element on a sub-tree with root x. +*/ + +node *Tree::minimum(node *x){ + + while(x->left != T_NIL){ + x = x->left; + } + return x; +} + +/* +* This function fixes the RB properties after an insertion. +* It's divided in three cases if the father of my node is RED, since we know that the actual node is RED. +* Case 1: If the father of node x is RED and it's uncle is red, then we paint them both black +* and the grandfather red. Then, x becomes the grandfather, so we can fix it. +* Case 2: If the uncle is not RED and x is a right child, we rotate left. +* Case 3: If the uncle is not RED and x is a left child, we paint x father to black and it's grandfather to RED, +* then we rotate right. +* Case 2 can fall in Case 3. On the end we paint the root black. +* There's two symetrical cases when the father is left or right. +*/ + +void Tree::insertFix_RB(node *x){ + + node *y; + + while(x->p->color == RED){ + + if(x->p == x->p->p->left){ + + // Case 1: + y = x->p->p->right; + if(y->color == RED){ + x->p->color = BLACK; + y->color = BLACK; + x->p->p->color = RED; + x = x->p->p; + } + + else{ + + // Case 2: + if(x == x->p->right){ + x = x->p; + rotacionar_esquerda(x); + } + + // Case 3: + + x->p->color = BLACK; + x->p->p->color = RED; + + rotacionar_direita(x->p->p); + } + } + + // Symetrical counterpart. + else{ + + // Case 1: + y = x->p->p->left; + + if(y->color == RED){ + x->p->color = BLACK; + y->color = BLACK; + x->p->p->color = RED; + x = x->p->p; + } + + else{ + // Case 2: + if(x == x->p->left){ + x = x->p; + rotacionar_direita(x); + } + + // Case 3: + x->p->color = BLACK; + x->p->p->color = RED; + rotacionar_esquerda(x->p->p); + } + } + } + this->root->color = BLACK; +} + +void Tree::deleteFix_RB(node *x){ + node *w; + while(x != this->root && x->color == BLACK){ + if(x == x->p->left){ + w = x->p->right; + if(w->color == RED){ + w->color = BLACK; + x->p->color = RED; + rotacionar_esquerda(x->p); + w = x->p->right; + } + if(w->left->color == BLACK && w->right->color == BLACK){ + w->color = RED; + x = x->p; + } + else{ + if(w->right->color == BLACK){ + w->left->color = BLACK; + w->left->color = RED; + rotacionar_direita(w); + w = x->p->right; + } + w->color = x->p->color; + x->p->color = BLACK; + w->right->color = BLACK; + rotacionar_esquerda(x->p); + x = this->root; + } + } + else{ + w = x->p->left; + if(w->color == RED){ + w->color = BLACK; + x->p->color = RED; + rotacionar_direita(x->p); + w = x->p->left; + } + if(w->right->color == BLACK && w->left->color == BLACK){ + w->color = RED; + x = x->p; + } + else{ + if(w->left->color == BLACK){ + w->right->color = BLACK; + w->right->color = RED; + rotacionar_esquerda(w); + w = x->p->left; + } + w->color = x->p->color; + x->p->color = BLACK; + w->left->color = BLACK; + rotacionar_direita(x->p); + x = this->root; + } + } + } + x->color = BLACK; +} + +// Prints the whole tree. + +void Tree::print(){ + printt(this->root, this->T_NIL); +} + + +// Allocates a node in the memory and returns it. + +node *criar_no(int x, node *T_NIL){ + node *no = (node*) malloc(sizeof(node)); + no->left = no->right = no->p = T_NIL; + no->value = x; + no->color = RED; + return no; +} + +// Prints the node by parameter, does a BFS to print by Level. +void printt(node *no, node *T_NIL){ + + if(no == NULL) return; + queue < int > sp; + queue < node* > q; + q.push(no); + sp.push(0); + + while(!q.empty()){ + + node *tmp = q.front(); + int spaces = sp.front(); + sp.pop(); + q.pop(); + + for(int i = 0;i < spaces;i++){ + cout << "-"; + } + + if(tmp->color == RED) cout << "\033[1;31m " << tmp->value << "\033[0m" << endl; + + else cout << tmp->value << endl; + + if(tmp->left != T_NIL) { + q.push(tmp->left); + sp.push(spaces+7); + } + + if(tmp->right != T_NIL){ + q.push(tmp->right); + sp.push(spaces+7); + } + } +} + + +// Cleans the tree. +void limpar(node *no, node *T_NIL){ + if(no == T_NIL) return; + limpar(no->left, T_NIL); + limpar(no->right, T_NIL); + free(no); +} \ No newline at end of file diff --git a/data structures/Red Black/CPP/arvore_rb_c.h b/data structures/Red Black/CPP/arvore_rb_c.h new file mode 100644 index 000000000..ec0bc59af --- /dev/null +++ b/data structures/Red Black/CPP/arvore_rb_c.h @@ -0,0 +1,47 @@ +/* +* Red-Black tree implemented for a College Work. +* No copyright included. +* Done by joaobnetto +*/ + +#include +#define BLACK 1 +#define RED 2 + +using namespace std; + + + +struct node{ + int value, color; + struct node *left, *right, *p; +}; + + +class Tree{ +private: + node *root; + node *T_NIL; +public: + Tree(); + ~Tree(); + void insert(int x); + void insertFix_RB(node *no); + void delet(node *z); + void deleteFix_RB(node *x); + void rotacionar_esquerda(node *no); + void rotacionar_direita(node *no); + void transplant(node *u, node *v); + node *minimum(node *x); + node *search(int x); + void print(); + +}; + +void imprime(node *no, node *T_NIL); + +void printt(node *no, node *T_NIL); + +node *criar_no(int x,node *T_NIL); + +void limpar(node *no, node *T_NIL); \ No newline at end of file diff --git a/data structures/hash/Makefile b/data structures/hash/Makefile new file mode 100644 index 000000000..c600c5508 --- /dev/null +++ b/data structures/hash/Makefile @@ -0,0 +1,6 @@ +Output:nameht + +nameht: main.cpp hashfunctions.cpp + g++ main.cpp hashfunctions.cpp -o nameht +clean: + rm *.o nameht diff --git a/data structures/hash/hash.h b/data structures/hash/hash.h new file mode 100644 index 000000000..7b77aa8cd --- /dev/null +++ b/data structures/hash/hash.h @@ -0,0 +1,19 @@ +#include +using namespace std; + +class Hash + { + private: + int size,count,Tcount,uns,suc; + string key,type; + float lf; + struct node** head; //pointer to hash table + public: + struct node** initialise(int size,string type); + int insert(string key,int Tcount,int count,struct node** head); + int find(string key); + void deletekey(string key); + float load_factor(int count); + struct node** rehash(int size,struct node** head); + void disp_stats(int count); + }; diff --git a/data structures/hash/hashfunctions.cpp b/data structures/hash/hashfunctions.cpp new file mode 100644 index 000000000..9dae62e9f --- /dev/null +++ b/data structures/hash/hashfunctions.cpp @@ -0,0 +1,187 @@ +#include +#include +#include +#include +#include +#include "hash.h" + +using namespace std; + +struct node + { + string name; + int frequency; + }; + +struct node** hash::initialise(int siz,string typ) //function to initialise hashtable + { + size=siz; + type=typ; + head=new node*[size]; + + uns=0; + suc=0; + + for(int i=0;iname=key; + temp->frequency=Tcount; + + return temp; + } + + +int hash::insert(string key,int Tcount,int count,struct node** head) //function to insert a node + { + + loadfactor=(float)count/size; + + if(loadfactor<0.75) + { + struct node* temp; + int index=Hashfunc(key); + temp=createnode(key,Tcount); + int a=index%size; + if(head[a]==NULL){ + head[a]=temp; + count++; + suc++; + return count;} + else + { + if(head[a]->name==key){ + + head[a]->frequency=head[a]->frequency+Tcount; + return count;} + else{ + int i=1; + int b=a; + while(head[b]!=NULL&&iname,head[i]->frequency,count,headnew); + } + i++; + } + head =headnew; + return head; + } + + +int hash::find(string key) //function to find given key and return its frequency + { + int a=Hashfunc(key); + a=a%size; + if(head[a]!=NULL) + { + if(head[a]->name==key) + return head[a]->frequency; + int i=1,b; + while(iname==key) + return head[b]->frequency; + else{ + i++; + + } + } + } + return 0; + } + +void hash::deletekey(string key) //function to delete a given key + { + int a=Hashfunc(key); + a=a%size; + int i=0,b; + if(head[a]!=NULL) + { + while(iname==key) + { + head[b]->name="deleted"; + head[b]->frequency=0; + cout<name<<" "<frequency< +#include +#include +#include +#include +#include "hash.h" +using namespace std; + +struct node //node to store data in record + { + string name; + int frequency; + }; + +int main(int argc,char* argv[]) + { + int c=atoi(argv[1]); + int size=atoi(argv[2]); //taking input through command line + string type=argv[3]; + + hash h; + + struct node** head=h.initialise(size,type); //pointer to hash table + + int year,Mcount,Tcount,Fcount; + string key; + int count=0; + ifstream f; + f.open("input1.txt"); //taking input from file + while(f>>year) + { + f>>Tcount; + f>>Mcount; + f>>Fcount; + f>>key; + if(key.length()>=5) + count=h.insert(key,Tcount,count,head); + } + + cout<<"Enter option\n"; + int option; + cin>>option; + float lf; + + switch(option) + { + + case 2:cout<<"Enter key\n"; + cin>>key; + cout<>key; + if(key.length()>=5) + { + count=h.insert(key,Tcount,count,head); + cout<>key; + h.deletekey(key); + break; + + case 5: lf=h.load_factor(count); + cout<>size; + h.rehash(size,head); + break; + + case 7:h.disp_stats(count); + break; + + } + + } diff --git a/data structures/hash/readme.txt b/data structures/hash/readme.txt new file mode 100644 index 000000000..c97b2c81e --- /dev/null +++ b/data structures/hash/readme.txt @@ -0,0 +1,30 @@ +Objective: To implement Hash ADT with closed Hashing. + +Further consider the field,Name N as a key. Assume that all keys at least 5 characters long and may discard keys/records +which are shorter than 5 characters. Implemented Hash table ADT with the necessary member +functions, + +• to initialize the hash table (HT) with a specific size and specific collision resolving technique +• to insert a record with the given key +• to delete a record with the given key +• to find a record with the given key +• to rehash the hash table when load factor ? > 0.75 +• to print the statistics of number of probes for unsuccessful U and successful S find operations +carried out so far and current load factor ? +format of execution: +./nameht option [SIZE] [KEY] [CR] +option: +1. to initialize hash table for specific SIZE and CR +2. to find a given KEY +3. to insert a given KEY +4. to delete a given KEY +5. to compute load factor +6. to rehash hash table to a given size SIZE +7. to display statistics +Arguments mentioned in [ ] brackets are optional. +Example: +./nameht 1 500 LP - to create a hash table with size 500 slots and linear probing resolving +technique +./nameht 2 “vijay kumar” - find the name “vijay kumar” in the hash table. If exists, print its +frequency +./nameht 4 arun - delete the record with Key “arun” \ No newline at end of file diff --git a/data structures/queue/c/queue.c b/data structures/queue/c/queue.c new file mode 100644 index 000000000..e5c252e5e --- /dev/null +++ b/data structures/queue/c/queue.c @@ -0,0 +1,120 @@ +#include +#include + +#define TRUE 1 +#define FALSE 0 + +/* a link in the queue, holds the info and point to the next Node*/ +typedef struct { + int info; +} DATA; + +typedef struct Node_t { + DATA data; + struct Node_t *prev; +} NODE; + +/* the HEAD of the Queue, hold the amount of node's that are in the queue*/ +typedef struct Queue { + NODE *head; + NODE *tail; + int size; + int limit; +} Queue; + +Queue *ConstructQueue(int limit); +void DestructQueue(Queue *queue); +int Enqueue(Queue *pQueue, NODE *item); +NODE *Dequeue(Queue *pQueue); +int isEmpty(Queue* pQueue); + +Queue *ConstructQueue(int limit) { + Queue *queue = (Queue*) malloc(sizeof (Queue)); + if (queue == NULL) { + return NULL; + } + if (limit <= 0) { + limit = 65535; + } + queue->limit = limit; + queue->size = 0; + queue->head = NULL; + queue->tail = NULL; + + return queue; +} + +void DestructQueue(Queue *queue) { + NODE *pN; + while (!isEmpty(queue)) { + pN = Dequeue(queue); + free(pN); + } + free(queue); +} + +int Enqueue(Queue *pQueue, NODE *item) { + /* Bad parameter */ + if ((pQueue == NULL) || (item == NULL)) { + return FALSE; + } + // if(pQueue->limit != 0) + if (pQueue->size >= pQueue->limit) { + return FALSE; + } + /*the queue is empty*/ + item->prev = NULL; + if (pQueue->size == 0) { + pQueue->head = item; + pQueue->tail = item; + + } else { + /*adding item to the end of the queue*/ + pQueue->tail->prev = item; + pQueue->tail = item; + } + pQueue->size++; + return TRUE; +} + +NODE * Dequeue(Queue *pQueue) { + /*the queue is empty or bad param*/ + NODE *item; + if (isEmpty(pQueue)) + return NULL; + item = pQueue->head; + pQueue->head = (pQueue->head)->prev; + pQueue->size--; + return item; +} + +int isEmpty(Queue* pQueue) { + if (pQueue == NULL) { + return FALSE; + } + if (pQueue->size == 0) { + return TRUE; + } else { + return FALSE; + } +} + +int main() { + int i; + Queue *pQ = ConstructQueue(7); + NODE *pN; + + for (i = 0; i < 9; i++) { + pN = (NODE*) malloc(sizeof (NODE)); + pN->data.info = 100 + i; + Enqueue(pQ, pN); + } + + while (!isEmpty(pQ)) { + pN = Dequeue(pQ); + printf("\nDequeued: %d", pN->data); + free(pN); + } + DestructQueue(pQ); + return (EXIT_SUCCESS); +} diff --git a/data structures/quick.cpp b/data structures/quick.cpp new file mode 100644 index 000000000..52ebcfcb5 --- /dev/null +++ b/data structures/quick.cpp @@ -0,0 +1,76 @@ +#include +#include + +void swap(int *x,int *y); +int choose_pivot(int i,int j ); +void quicksort(int list[],int m,int n); +void display(int list[],const int n); + +void main() +{ + const int SIZE = 10; + int list[SIZE]; + + int i = 0; + + /* generates random numbers and fill the list */ + for(i = 0; i < SIZE; i++ ) + list[i] = rand(); + + printf("The list before sorting is:\n"); + display(list,SIZE); + + /* sort the list using quicksort algorithm */ + quicksort(list,0,SIZE-1); + + printf("The list after sorting:\n"); + display(list,SIZE); +} + +void swap(int *x,int *y) +{ + int temp; + temp = *x; + *x = *y; + *y = temp; +} + +int choose_pivot(int i,int j ) +{ + return((i+j) /2); +} + +void quicksort(int list[],int m,int n) +{ + int key,i,j,k; + if( m < n) + { + k = choose_pivot(m,n); + swap(&list[m],&list[k]); + key = list[m]; + i = m+1; + j = n; + while(i <= j) + { + while((i <= n) && (list[i] <= key)) + i++; + while((j >= m) && (list[j] > key)) + j--; + if( i < j) + swap(&list[i],&list[j]); + } + /* swap two elements */ + swap(&list[m],&list[j]); + + /* recursively sort the lesser list */ + quicksort(list,m,j-1); + quicksort(list,j+1,n); + } +} +void display(int list[],const int n) +{ + int i; + for(i=0; i pivot] + return quick_sort(left) + middle + quick_sort(right) + +print (quick_sort([5,2,8,3,9,12,43])) # This will print [2,3,5,8,9,12,43] diff --git a/data structures/shell.cpp b/data structures/shell.cpp new file mode 100644 index 000000000..0d575cd1b --- /dev/null +++ b/data structures/shell.cpp @@ -0,0 +1,45 @@ +#include +using namespace std; + +int shellSort(int arr[], int n) +{ + for (int gap = n/2; gap > 0; gap /= 2) + { + for (int i = gap; i < n; i += 1) + { + + int temp = arr[i]; + + + int j; + for (j = i; j >= gap && arr[j - gap] > temp; j -= gap) + arr[j] = arr[j - gap]; + + + arr[j] = temp; + } + } + return 0; +} + +void printArray(int arr[], int n) +{ + for (int i=0; idata = data; + + // Initialize left and right children as NULL + node->left = NULL; + node->right = NULL; + return(node); +} + + +int main() +{ + /*create root*/ + struct node *root = newNode(1); + /* following is the tree after above statement + + 1 + / \ + NULL NULL + */ + + + root->left = newNode(2); + root->right = newNode(3); + /* 2 and 3 become left and right children of 1 + 1 + / \ + 2 3 + / \ / \ + NULL NULL NULL NULL + */ + + + root->left->left = newNode(4); + /* 4 becomes left child of 2 + 1 + / \ + 2 3 + / \ / \ + 4 NULL NULL NULL + / \ + NULL NULL + */ + + getchar(); + return 0; +} diff --git a/graph/graph coloring/square_grid_multidim.cpp b/graph/graph coloring/square_grid_multidim.cpp new file mode 100644 index 000000000..bd9884557 --- /dev/null +++ b/graph/graph coloring/square_grid_multidim.cpp @@ -0,0 +1,21 @@ +// this is an algorithm for colouring nodes in regular square grid +#include + +int colour(int position[], int dimension){ + int result = 0; + for(int i = 1; i <= dimension; i++) + result += i * position[i]; + return result % (2 * dimension + 1); +} + +int main(){ + + int x[] = {1,1}; + int y[] = {1,2}; + int z[] = {2,1}; + + + std::cout << colour(x,2) << std::endl; + std::cout << colour(y,2) << std::endl; + std::cout << colour(z,2) << std::endl; +} diff --git a/quick.cpp b/quick.cpp new file mode 100644 index 000000000..52ebcfcb5 --- /dev/null +++ b/quick.cpp @@ -0,0 +1,76 @@ +#include +#include + +void swap(int *x,int *y); +int choose_pivot(int i,int j ); +void quicksort(int list[],int m,int n); +void display(int list[],const int n); + +void main() +{ + const int SIZE = 10; + int list[SIZE]; + + int i = 0; + + /* generates random numbers and fill the list */ + for(i = 0; i < SIZE; i++ ) + list[i] = rand(); + + printf("The list before sorting is:\n"); + display(list,SIZE); + + /* sort the list using quicksort algorithm */ + quicksort(list,0,SIZE-1); + + printf("The list after sorting:\n"); + display(list,SIZE); +} + +void swap(int *x,int *y) +{ + int temp; + temp = *x; + *x = *y; + *y = temp; +} + +int choose_pivot(int i,int j ) +{ + return((i+j) /2); +} + +void quicksort(int list[],int m,int n) +{ + int key,i,j,k; + if( m < n) + { + k = choose_pivot(m,n); + swap(&list[m],&list[k]); + key = list[m]; + i = m+1; + j = n; + while(i <= j) + { + while((i <= n) && (list[i] <= key)) + i++; + while((j >= m) && (list[j] > key)) + j--; + if( i < j) + swap(&list[i],&list[j]); + } + /* swap two elements */ + swap(&list[m],&list[j]); + + /* recursively sort the lesser list */ + quicksort(list,m,j-1); + quicksort(list,j+1,n); + } +} +void display(int list[],const int n) +{ + int i; + for(i=0; i