diff --git a/0-1 knapsack.cpp/0-1 knapsack.cpp b/0-1 knapsack.cpp/0-1 knapsack.cpp new file mode 100644 index 0000000..12459c2 --- /dev/null +++ b/0-1 knapsack.cpp/0-1 knapsack.cpp @@ -0,0 +1,46 @@ +#include +using namespace std; + +// A utility function that returns +// maximum of two integers +int max(int a, int b) { return (a > b) ? a : b; } + +// Returns the maximum value that +// can be put in a knapsack of capacity W +int knapSack(int W, int wt[], int val[], int n) +{ + + // Base Case + if (n == 0 || W == 0) + return 0; + + // If weight of the nth item is more + // than Knapsack capacity W, then + // this item cannot be included + // in the optimal solution + if (wt[n - 1] > W) + return knapSack(W, wt, val, n - 1); + + // Return the maximum of two cases: + // (1) nth item included + // (2) not included + else + return max( + val[n - 1] + + knapSack(W - wt[n - 1], + wt, val, n - 1), + knapSack(W, wt, val, n - 1)); +} + +// Driver code +int main() +{ + int val[] = { 60, 100, 120 }; + int wt[] = { 10, 20, 30 }; + int W = 50; + int n = sizeof(val) / sizeof(val[0]); + cout << knapSack(W, wt, val, n); + return 0; +} + +// This diff --git a/Armstrong Number/Armstrong.java b/Armstrong Number/Armstrong.java new file mode 100644 index 0000000..204cd93 --- /dev/null +++ b/Armstrong Number/Armstrong.java @@ -0,0 +1,44 @@ +import java.util.Scanner; +import java.lang.Math; +public class ArmstsrongNumberExample { + //function to check if the number is Armstrong or not + static boolean isArmstrong(int n) { + int temp, digits=0, last=0, sum=0; + //assigning n into a temp variable + temp=n; + //loop execute until the condition becomes false + while(temp>0) { + temp = temp/10; + digits++; + } + temp = n; + while(temp>0) { + //determines the last digit from the number + last = temp % 10; + //calculates the power of a number up to digit times and add the resultant to the sum variable + sum += (Math.pow(last, digits)); + //removes the last digit + temp = temp/10; + } + //compares the sum with n + if(n==sum) + //returns if sum and n are equal + return true; + //returns false if sum and n are not equal + else return false; +} +//driver code +public static void main(String args[]) { + int num; + Scanner sc= new Scanner(System.in); + System.out.print("Enter the limit: "); + //reads the limit from the user + num=sc.nextInt(); + System.out.println("Armstrong Number up to "+ num + " are: "); + for(int i=0; i<=num; i++) + //function calling + if(isArmstrong(i)) + //prints the armstrong numbers + System.out.print(i+ ", "); + } +} diff --git a/Armstrong Number/armstrong_number.js b/Armstrong Number/armstrong_number.js new file mode 100644 index 0000000..bfdbd18 --- /dev/null +++ b/Armstrong Number/armstrong_number.js @@ -0,0 +1,23 @@ +// program to check an Armstrong number of three digits + +let sum = 0; +const number = prompt('Enter a three-digit positive integer: '); + +// create a temporary variable +let temp = number; +while (temp > 0) { + // finding the one's digit + let remainder = temp % 10; + + sum += remainder * remainder * remainder; + + // removing last digit from the number + temp = parseInt(temp / 10); // convert float into integer +} +// check the condition +if (sum == number) { + console.log(`${number} is an Armstrong number`); +} +else { + console.log(`${number} is not an Armstrong number.`); +} diff --git a/Binary Insertion Sort/Binary-Insertion-Sort.py b/Binary Insertion Sort/Binary-Insertion-Sort.py new file mode 100644 index 0000000..4b008b1 --- /dev/null +++ b/Binary Insertion Sort/Binary-Insertion-Sort.py @@ -0,0 +1,38 @@ +# Python Program implementation +# of binary insertion sort + +def binary_search(arr, val, start, end): + # we need to distinugish whether we should insert + # before or after the left boundary. + # imagine [0] is the last step of the binary search + # and we need to decide where to insert -1 + if start == end: + if arr[start] > val: + return start + else: + return start+1 + + # this occurs if we are moving beyond left\'s boundary + # meaning the left boundary is the least position to + # find a number greater than val + if start > end: + return start + + mid = (start+end)/2 + if arr[mid] < val: + return binary_search(arr, val, mid+1, end) + elif arr[mid] > val: + return binary_search(arr, val, start, mid-1) + else: + return mid + +def insertion_sort(arr): + for i in xrange(1, len(arr)): + val = arr[i] + j = binary_search(arr, val, 0, i-1) + arr = arr[:j] + [val] + arr[j:i] + arr[i+1:] + return arr + +print("Sorted array:") +print insertion_sort([37, 23, 0, 17, 12, 72, 31, + 46, 100, 88, 54]) diff --git a/BinarySearch/binarysearch.js b/BinarySearch/binarysearch.js new file mode 100644 index 0000000..c2796fb --- /dev/null +++ b/BinarySearch/binarysearch.js @@ -0,0 +1,37 @@ + diff --git a/Bubble Sort/BubbleSort.js b/Bubble Sort/BubbleSort.js new file mode 100644 index 0000000..bef768e --- /dev/null +++ b/Bubble Sort/BubbleSort.js @@ -0,0 +1,45 @@ +function swap(arr, xp, yp) +{ + var temp = arr[xp]; + arr[xp] = arr[yp]; + arr[yp] = temp; +} + +// An optimized version of Bubble Sort +function bubbleSort( arr, n) +{ +var i, j; +for (i = 0; i < n-1; i++) +{ + for (j = 0; j < n-i-1; j++) + { + if (arr[j] > arr[j+1]) + { + swap(arr,j,j+1); + + } + } + +} +} + +/* Function to print an array */ +function printArray(arr, size) +{ + var i; + for (i=0; i < size; i++) + document.write(arr[i]+ " "); + document.write("\n"); +} + +// Driver program to test above functions +var arr = [64, 34, 25, 12, 22, 11, 90]; + var n = 7; + document.write("UnSorted array: \n"); + printArray(arr, n); + + bubbleSort(arr, n); + document.write("Sorted array: \n"); + printArray(arr, n); + + diff --git a/Bucket Sort/Bucket-sort.cpp b/Bucket Sort/Bucket-sort.cpp new file mode 100644 index 0000000..c486bef --- /dev/null +++ b/Bucket Sort/Bucket-sort.cpp @@ -0,0 +1,46 @@ +// C++ program to sort an +// array using bucket sort +#include +#include +#include +using namespace std; + +// Function to sort arr[] of +// size n using bucket sort +void bucketSort(float arr[], int n) +{ + + // 1) Create n empty buckets + vector b[n]; + + // 2) Put array elements + // in different buckets + for (int i = 0; i < n; i++) { + int bi = n * arr[i]; // Index in bucket + b[bi].push_back(arr[i]); + } + + // 3) Sort individual buckets + for (int i = 0; i < n; i++) + sort(b[i].begin(), b[i].end()); + + // 4) Concatenate all buckets into arr[] + int index = 0; + for (int i = 0; i < n; i++) + for (int j = 0; j < b[i].size(); j++) + arr[index++] = b[i][j]; +} + +/* Driver program to test above function */ +int main() +{ + float arr[] + = { 0.897, 0.565, 0.656, 0.1234, 0.665, 0.3434 }; + int n = sizeof(arr) / sizeof(arr[0]); + bucketSort(arr, n); + + cout << "Sorted array is \n"; + for (int i = 0; i < n; i++) + cout << arr[i] << " "; + return 0; +} diff --git a/Data Structure/Binary Indexed Tree ( Fenwick Tree )/Binary_Indexed_Tree.cpp b/Data Structure/Binary Indexed Tree ( Fenwick Tree )/Binary_Indexed_Tree.cpp new file mode 100644 index 0000000..1069d4c --- /dev/null +++ b/Data Structure/Binary Indexed Tree ( Fenwick Tree )/Binary_Indexed_Tree.cpp @@ -0,0 +1,50 @@ +#include +using namespace std; + +#define Least_Significant_Bit(i) (i) & -(i) + +vector Binary_Indexed_Tree; + +int TREE_SIZE = 1e5 + 10; + +void update(int index, int value) { + while(index <= TREE_SIZE) { + Binary_Indexed_Tree[index] += value; + index += Least_Significant_Bit(index); + } +} + +int query(int index) { + int sum = 0; + while(index > 0) { + sum += Binary_Indexed_Tree[index]; + index -= Least_Significant_Bit(index); + } + return sum; +} + +int main() { + ios_base::sync_with_stdio(false); + cin.tie(nullptr); + + Binary_Indexed_Tree.assign(TREE_SIZE, 0); + int n; + cin >> n; + for(int i = 1; i <= n; i++) { + string operation; + cin >> operation; + if(operation == "U") { + /// Update + int index, value; + cin >> index >> value; + update(index, value); + } + if(operation == "Q") { + /// Query + int index; + cin >> index; + cout << query(index) << "\n"; + } + } + return 0; +} diff --git a/Dijkstra's Algorithm/dijkstra.js b/Dijkstra's Algorithm/dijkstra.js new file mode 100644 index 0000000..9bb6e98 --- /dev/null +++ b/Dijkstra's Algorithm/dijkstra.js @@ -0,0 +1,30 @@ +djikstraAlgorithm(startNode) { + let distances = {}; + + // Stores the reference to previous nodes + let prev = {}; + let pq = new PriorityQueue(this.nodes.length * this.nodes.length); + + // Set distances to all nodes to be infinite except startNode + distances[startNode] = 0; + pq.enqueue(startNode, 0); + this.nodes.forEach(node => { + if (node !== startNode) distances[node] = Infinity; + prev[node] = null; + }); + + while (!pq.isEmpty()) { + let minNode = pq.dequeue(); + let currNode = minNode.data; + let weight = minNode.priority; + this.edges[currNode].forEach(neighbor => { + let alt = distances[currNode] + neighbor.weight; + if (alt < distances[neighbor.node]) { + distances[neighbor.node] = alt; + prev[neighbor.node] = currNode; + pq.enqueue(neighbor.node, distances[neighbor.node]); + } + }); + } + return distances; +} diff --git a/Fibonacci series/fibonacci.c b/Fibonacci series/fibonacci.c new file mode 100644 index 0000000..b59d44f --- /dev/null +++ b/Fibonacci series/fibonacci.c @@ -0,0 +1,14 @@ +#include +int fib(int n) +{ + if(n<=1) + return n; + return fib(n-1)+fib(n-2); +} +int main() +{ + int a; + scanf("%d",&a); + printf("%d",fib(a)); + return 0; +} diff --git a/Fibonacci series/fibonacci.cpp b/Fibonacci series/fibonacci.cpp new file mode 100644 index 0000000..014ee91 --- /dev/null +++ b/Fibonacci series/fibonacci.cpp @@ -0,0 +1,16 @@ +#include +using namespace std; +int main() { + int n1=0,n2=1,n3,i,number; + cout<<"Enter the number of elements: "; + cin>>number; + cout< +// declaration of the variables +var n1 = 0, n2 = 1, next_num, i; +var num = parseInt (prompt (" Enter the limit for Fibonacci Series ")); +document.write( "Fibonacci Series: "); +for ( i = 1; i <= num; i++) +{ document.write ("
" + n1); // print the n1 + next_num = n1 + n2; // sum of n1 and n2 into the next_num + + n1 = n2; // assign the n2 value into n2 + n2 = next_num; // assign the next_num into n2 +} + + diff --git a/Jump Search/jump.py b/Jump Search/jump.py new file mode 100644 index 0000000..bf3b4d5 --- /dev/null +++ b/Jump Search/jump.py @@ -0,0 +1,46 @@ +# Python3 code to implement Jump Search +import math + +def jumpSearch( arr , x , n ): + + # Finding block size to be jumped + step = math.sqrt(n) + + # Finding the block where element is + # present (if it is present) + prev = 0 + while arr[int(min(step, n)-1)] < x: + prev = step + step += math.sqrt(n) + if prev >= n: + return -1 + + # Doing a linear search for x in + # block beginning with prev. + while arr[int(prev)] < x: + prev += 1 + + # If we reached next block or end + # of array, element is not present. + if prev == min(step, n): + return -1 + + # If element is found + if arr[int(prev)] == x: + return prev + + return -1 + +# Driver code to test function +arr = [ 0, 1, 1, 2, 3, 5, 8, 13, 21, + 34, 55, 89, 144, 233, 377, 610 ] +x = 55 +n = len(arr) + +# Find the index of 'x' using Jump Search +index = jumpSearch(arr, x, n) + +# Print the index where 'x' is located +print("Number" , x, "is at index" ,"%.0f"%index) + +# This code is contributed by "Sharad_Bhardwaj". diff --git a/Jump Search/jumpSearch.js b/Jump Search/jumpSearch.js new file mode 100644 index 0000000..af2b978 --- /dev/null +++ b/Jump Search/jumpSearch.js @@ -0,0 +1,26 @@ +function jumpSearch(arr, target) { + + let len = arr.length + let step = Math.floor(Math.sqrt(len)); + let blockStart = 0, currentStep = step; + + while (arr[Math.min(currentStep, len) - 1] < target) { + blockStart = currentStep; + currentStep += step; + + if (blockStart >= len) + return -1; + } + + while (arr[blockStart] < target) + { + blockStart++; + if (blockStart == Math.min(currentStep, len)) + return -1; + } + + if (arr[blockStart] == target) + return blockStart + else + return -1; +} diff --git a/KMP Algorithm/KMP_1.java b/KMP Algorithm/KMP_1.java new file mode 100644 index 0000000..afabf65 --- /dev/null +++ b/KMP Algorithm/KMP_1.java @@ -0,0 +1,47 @@ +public String shortestPalindrome(String s) { + String temp = s + "#" + new StringBuilder(s).reverse().toString(); + int[] table = getTable(temp); + + //get the maximum palin part in s starts from 0 + return new StringBuilder(s.substring(table[table.length - 1])).reverse().toString() + s; +} + +public int[] getTable(String s){ + //get lookup table + int[] table = new int[s.length()]; + + //pointer that points to matched char in prefix part + + int index = 0; + //skip index 0, we will not match a string with itself + for(int i = 1; i < s.length(); i++){ + if(s.charAt(index) == s.charAt(i)){ + //we can extend match in prefix and postfix + table[i] = table[i-1] + 1; + index ++; + }else{ + //match failed, we try to match a shorter substring + + //by assigning index to table[i-1], we will shorten the match string length, and jump to the + //prefix part that we used to match postfix ended at i - 1 + index = table[i-1]; + + while(index > 0 && s.charAt(index) != s.charAt(i)){ + //we will try to shorten the match string length until we revert to the beginning of match (index 1) + index = table[index-1]; + } + + //when we are here may either found a match char or we reach the boundary and still no luck + //so we need check char match + if(s.charAt(index) == s.charAt(i)){ + //if match, then extend one char + index ++ ; + } + + table[i] = index; + } + + } + + return table; +} diff --git a/Linear Search/linearsearch.js b/Linear Search/linearsearch.js new file mode 100644 index 0000000..5252e70 --- /dev/null +++ b/Linear Search/linearsearch.js @@ -0,0 +1,8 @@ +function linearSearch(arr, key){ + for(let i = 0; i < arr.length; i++){ + if(arr[i] === key){ + return i + } + } + return -1 +} diff --git a/Linked LIst/reverse-a-inkedlist.js b/Linked LIst/reverse-a-inkedlist.js new file mode 100644 index 0000000..a5a4d35 --- /dev/null +++ b/Linked LIst/reverse-a-inkedlist.js @@ -0,0 +1,47 @@ +// JavaScript program for reversing the linked list + +var head; + + class Node { + constructor(val) { + this.data = val; + this.next = null; + } + } + + /* Function to reverse the linked list */ + function reverse(node) { + var prev = null; + var current = node; + var next = null; + while (current != null) { + next = current.next; + current.next = prev; + prev = current; + current = next; + } + node = prev; + return node; + } + + // prints content of var linked list + function printList(node) { + while (node != null) { + document.write(node.data + " "); + node = node.next; + } + } + + // Driver Code + + head = new Node(85); + head.next = new Node(15); + head.next.next = new Node(4); + head.next.next.next = new Node(20); + + document.write("Given Linked list
"); + printList(head); + head = reverse(head); + document.write("
"); + document.write("Reversed linked list
"); + printList(head); \ No newline at end of file diff --git a/Luhn algorithm/Luhn.py b/Luhn algorithm/Luhn.py new file mode 100644 index 0000000..c267c9b --- /dev/null +++ b/Luhn algorithm/Luhn.py @@ -0,0 +1,23 @@ +""" + Luhn algorithm or Luhn formula + Checksum algorithm. + Source:https://en.wikipedia.org/wiki/Luhn_algorithm + +""" + +def luhn(input_number): + + input_number = [int(i) for i in str(input_number)] + input_number.reverse() + + sum_answer = 0 + for i, number in enumerate(input_number): + temp = number + if i % 2 == 0: + temp = number * 2 + if temp > 9: + temp -= 9 + + sum_answer = sum_answer + temp + + return sum_answer % 10 == 0 diff --git a/MST/Kruskals.cpp b/MST/Kruskals.cpp new file mode 100644 index 0000000..524bf1a --- /dev/null +++ b/MST/Kruskals.cpp @@ -0,0 +1,84 @@ +#include +using namespace std; +class edge +{ + public: + int src; + int dest; + int weight; +}; +bool comapare(edge e1,edge e2) +{ + return (e1.weight >v>>e; + edge *edges = new edge[e]; + for(int i=0;i>x>>y>>z; + edges[i].src =x; + edges[i].dest =y; + edges[i].weight =z; + } + edge *output =kruskal(edges,v,e); + for(int i=0;i +using namespace std; +int getminVertex(vector &weight,vector &visited,int n) +{ + int mini = -1; + for(int i=0;i> a,int n,int e) +{ + vector weight(n,INT_MAX); + vector parent(n); + vector visited(n,false); + parent[0]=-1; + weight[0]=1; + for(int i=0;i a[minvertex][j]) + { + weight[j] = a[minvertex][j]; + parent[j] =minvertex; + } + } + } + } + for(int i=1;i>n>>e; + vector> mat(n,vector (n)); + int x,y,weight; + for(int i=0;i>x>>y>>weight; + mat[x][y]=weight; + mat[y][x]=weight; + + } + prims(mat,n,e); + + + return 0; +} \ No newline at end of file diff --git a/MST/prims.py b/MST/prims.py new file mode 100644 index 0000000..ce969f1 --- /dev/null +++ b/MST/prims.py @@ -0,0 +1,37 @@ +# Prim's Algorithm in Python + +INF = 9999999 +# number of vertices in graph +N = 5 +#creating graph by adjacency matrix method +G = [[0, 19, 5, 0, 0], + [19, 0, 5, 9, 2], + [5, 5, 0, 1, 6], + [0, 9, 1, 0, 1], + [0, 2, 6, 1, 0]] + +selected_node = [0, 0, 0, 0, 0] + +no_edge = 0 + +selected_node[0] = True + +# printing for edge and weight +print("Edge : Weight\n") +while (no_edge < N - 1): + + minimum = INF + a = 0 + b = 0 + for m in range(N): + if selected_node[m]: + for n in range(N): + if ((not selected_node[n]) and G[m][n]): + # not in selected and there is an edge + if minimum > G[m][n]: + minimum = G[m][n] + a = m + b = n + print(str(a) + "-" + str(b) + ":" + str(G[a][b])) + selected_node[b] = True + no_edge += 1 diff --git a/MergeSort/MERGE_1.java b/MergeSort/MERGE_1.java new file mode 100644 index 0000000..d0b96ae --- /dev/null +++ b/MergeSort/MERGE_1.java @@ -0,0 +1,40 @@ +class Solution { + public int[] sortArray(int[] nums) { + int N = nums.length; + mergeSort(nums, 0, N-1); + return nums; + } + + + void mergeSort(int[] nums, int start, int end){ + if (end - start+1 <= 1) return; //Already sorted. + int mi = start + (end - start)/ 2; + mergeSort(nums, start, mi); + mergeSort(nums, mi+1, end); + merge(nums, start,mi, end); + } + + void merge(int[] nums, int start, int mi, int end){ + int lp = start; + int rp = mi + 1; + int[] buffer = new int[end-start+1]; + int t = 0; //buffer pointer + + while (lp <= mi && rp <= end){ + if (nums[lp] < nums[rp]){ + buffer[t++] = nums[lp++]; + }else{ + buffer[t++] = nums[rp++]; + } + } + + while (lp <= mi) buffer[t++] = nums[lp++]; + while (rp <= end) buffer[t++] = nums[rp++]; + //Now copy sorted buffer into original array + for (int i = start; i <= end; i++){ + nums[i] = buffer[i-start]; + } + } + + +} diff --git a/MergeSort/MergeSort.cpp b/MergeSort/MergeSort.cpp new file mode 100755 index 0000000..2b88af6 --- /dev/null +++ b/MergeSort/MergeSort.cpp @@ -0,0 +1,62 @@ +#include +#include +#include +#include +#include +#include +using namespace std; +using LL = long long; +using ULL = unsigned long long; +#define FOR(i,a,b) for(int i = a; i < b; i++) +#define DFOR(i,a,b) for(int i = a; i > b; i--) + +void merge(int ar[],int lo,int mid,int hi){ + int p1=lo,p2=mid+1,temp[hi-lo+1],k=0; + while(p1<=mid && p2<=hi){ + if(ar[p1] < ar[p2]){ + temp[k++] = ar[p1++]; + } + else{ + temp[k++] = ar[p2++]; + } + } + while(p1<=mid){ + temp[k++] = ar[p1++]; + } + while(p2<=hi){ + temp[k++] = ar[p2++]; + } + FOR(i,0,hi-lo+1){ + ar[i+lo] = temp[i]; + } +} + +void MS(int ar[],int lo,int hi){ + if(lo==hi){ + return; + } + int mid = (lo+hi)/2; + MS(ar,lo,mid); + MS(ar,mid+1,hi); + merge(ar,lo,mid,hi); +} +int main(){ + ios_base::sync_with_stdio(0); + cin.tie(0); + cout.tie(0); + int t; + cin >> t; + FOR(i,0,t){ + int n,k; + cin >> n >> k; + int a[n]; + FOR(j,0,n){ + cin >> a[j]; + } + MS(a,0,n-1); + FOR(j,0,n){ + cout << a[j] << " "; + } + } + return 0; +} \ No newline at end of file diff --git a/QuickSort/QuickSort.java b/QuickSort/QuickSort.java new file mode 100644 index 0000000..2c1da03 --- /dev/null +++ b/QuickSort/QuickSort.java @@ -0,0 +1,58 @@ +public class Quick +{ + /* function that consider last element as pivot, +place the pivot at its exact position, and place +smaller elements to left of pivot and greater +elements to right of pivot. */ +int partition (int a[], int start, int end) +{ + int pivot = a[end]; // pivot element + int i = (start - 1); + + for (int j = start; j <= end - 1; j++) + { + // If current element is smaller than the pivot + if (a[j] < pivot) + { + i++; // increment index of smaller element + int t = a[i]; + a[i] = a[j]; + a[j] = t; + } + } + int t = a[i+1]; + a[i+1] = a[end]; + a[end] = t; + return (i + 1); +} + +/* function to implement quick sort */ +void quick(int a[], int start, int end) /* a[] = array to be sorted, start = Starting index, end = Ending index */ +{ + if (start < end) + { + int p = partition(a, start, end); //p is partitioning index + quick(a, start, p - 1); + quick(a, p + 1, end); + } +} + +/* function to print an array */ +void printArr(int a[], int n) +{ + int i; + for (i = 0; i < n; i++) + System.out.print(a[i] + " "); +} + public static void main(String[] args) { + int a[] = { 13, 18, 27, 2, 19, 25 }; + int n = a.length; + System.out.println("\nBefore sorting array elements are - "); + Quick q1 = new Quick(); + q1.printArr(a, n); + q1.quick(a, 0, n - 1); + System.out.println("\nAfter sorting array elements are - "); + q1.printArr(a, n); + System.out.println(); + } +} diff --git a/README.md b/README.md index 37f16dc..c92c462 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,19 @@ # AlgorithmBank Help us make a deposit of algorithms. -#Rules to Contribute- - +# Rules to Contribute +-Check the issues section for new issues.
-Add alogorithms under Algorithm Name/Algorithm File.
-You can contribute in any language.
-You can also raise issues to verify with us.
--You can edit existing algorithms,if it is not right, But please raise an issue if you are doing this to verify with us. - +-You can edit existing algorithms,if it is not right. +# Contributors + + + + -If you need the PR for HacktoberFest 2021, plaese comment it and let us know. +If you need the PR for HacktoberFest 2021, please comment it and let us know. Happy coding. diff --git a/Radix sort/Radix_sort.cpp b/Radix sort/Radix_sort.cpp new file mode 100644 index 0000000..927cf97 --- /dev/null +++ b/Radix sort/Radix_sort.cpp @@ -0,0 +1,47 @@ +#include +#include +#include +using namespace std; +void display(int *array, int size) { + for(int i = 0; i pocket[10]; + for(i = 0; i< max; i++) { + m = pow(10, i+1); + p = pow(10, i); + for(j = 0; j> n; + cout << "Enter the maximum digit of elements: "; + cin >> max; + int arr[n]; + cout << "Enter elements:" << endl; + for(int i = 0; i> arr[i]; + } + cout << "Data before Sorting: "; + display(arr, n); + radixSort(arr, n, max); + cout << "Data after Sorting: "; + display(arr, n); +} diff --git a/Selection sort/SelSort.java b/Selection sort/SelSort.java new file mode 100644 index 0000000..24b148c --- /dev/null +++ b/Selection sort/SelSort.java @@ -0,0 +1,32 @@ +public class SelectionSortExample { + public static void selectionSort(int[] arr){ + for (int i = 0; i < arr.length - 1; i++) + { + int index = i; + for (int j = i + 1; j < arr.length; j++){ + if (arr[j] < arr[index]){ + index = j;//searching for lowest index + } + } + int smallerNumber = arr[index]; + arr[index] = arr[i]; + arr[i] = smallerNumber; + } + } + + public static void main(String a[]){ + int[] arr1 = {9,14,3,2,43,11,58,22}; + System.out.println("Before Selection Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + System.out.println(); + + selectionSort(arr1);//sorting array using selection sort + + System.out.println("After Selection Sort"); + for(int i:arr1){ + System.out.print(i+" "); + } + } +} diff --git a/Tree/tree_dsa.cpp b/Tree/tree_dsa.cpp new file mode 100644 index 0000000..5b96ed8 --- /dev/null +++ b/Tree/tree_dsa.cpp @@ -0,0 +1,129 @@ +#include +using namespace std; +#define fast ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL); +typedef long long ll; +const ll mod=1e9+7; +//<------disjoint set-union------> +vectorparent,size; +void make_set(int v) { + parent[v] = v; + size[v] = 1; +} + +void union_sets(int a, int b) { + a = find_set(a); + b = find_set(b); + if (a != b) { + if (size[a] < size[b]) + swap(a, b); + parent[b] = a; + size[a] += size[b]; + } +} + +int find_set(int v) { + if (v == parent[v]) + return v; + return find_set(parent[v]); +} + +//<-----------fenwick tree---------> +struct FenwickTree { + vector bit; // binary indexed tree + int n; + + FenwickTree(int n) { + this->n = n; + bit.assign(n, 0); + } + + FenwickTree(vector a) : FenwickTree(a.size()) { + for (size_t i = 0; i < a.size(); i++) + add(i, a[i]); + } + + int sum(int r) { + int ret = 0; + for (; r >= 0; r = (r & (r + 1)) - 1) + ret += bit[r]; + return ret; + } + + int sum(int l, int r) { + return sum(r) - sum(l - 1); + } + + void add(int idx, int delta) { + for (; idx < n; idx = idx | (idx + 1)) + bit[idx] += delta; + } +}; + +//<-------------square root decomposition--------------> + +void sqrt_decmpO(){ +//input data +int n; +vector a (n); + +// preprocessing +int len = (int) sqrt (n + .0) + 1; // size of the block and the number of blocks +vector b (len); +for (int i=0; i +int MAXN; +int n; +vectort(4*MAXN); +void build(int a[], int v, int tl, int tr) { + if (tl == tr) { + t[v] = a[tl]; + } else { + int tm = (tl + tr) / 2; + build(a, v*2, tl, tm); + build(a, v*2+1, tm+1, tr); + t[v] = t[v*2] + t[v*2+1]; + } +} +int sum(int v, int tl, int tr, int l, int r) { + if (l > r) + return 0; + if (l == tl && r == tr) { + return t[v]; + } + int tm = (tl + tr) / 2; + return sum(v*2, tl, tm, l, min(r, tm)) + + sum(v*2+1, tm+1, tr, max(l, tm+1), r); +} +void update(int v, int tl, int tr, int pos, int new_val) { + if (tl == tr) { + t[v] = new_val; + } else { + int tm = (tl + tr) / 2; + if (pos <= tm) + update(v*2, tl, tm, pos, new_val); + else + update(v*2+1, tm+1, tr, pos, new_val); + t[v] = t[v*2] + t[v*2+1]; + } +} diff --git a/adler32 hash/adler32.py b/adler32 hash/adler32.py new file mode 100644 index 0000000..3e886cf --- /dev/null +++ b/adler32 hash/adler32.py @@ -0,0 +1,18 @@ +''' +Old database hashfunction. +Source: +https://en.wikipedia.org/wiki/Adler-32 +https://www.youtube.com/watch?v=BWqH4O7OuyY +''' + +def adler32(input_plain_text): + A = 1 + B = 0 + m = 65521 + for char in input_plain_text: + A = (A + ord(char)) % m + B = (B + A) % m + hash = (B << 16) | A + return hash + + diff --git a/djb2 hash/djb2.py b/djb2 hash/djb2.py new file mode 100644 index 0000000..e4098ae --- /dev/null +++ b/djb2 hash/djb2.py @@ -0,0 +1,19 @@ +''' +Old hashfunction. + +Explaination: +(magic_hash_nr + (magic_hash_nr << 5)) is equivalent to (magic_hash_nr*33). +This because the bit shift of <<5 is multiplying by 32 then we add another one. + +Source: +http://www.cse.yorku.ca/~oz/hash.html +https://stackoverflow.com/questions/1579721/why-are-5381-and-33-so-important-in-the-djb2-algorithm +''' + + +def djb2(input_plain_text): + magic_hash_nr = 5381 + for char in input_plain_text: + magic_hash_nr = ord(char) + (magic_hash_nr + (magic_hash_nr << 5)) + magic_hash_nr = magic_hash_nr & 0xFFFFFFFF + return magic_hash_nr \ No newline at end of file diff --git a/hufman code/hufman_code.c b/hufman code/hufman_code.c new file mode 100644 index 0000000..1972c04 --- /dev/null +++ b/hufman code/hufman_code.c @@ -0,0 +1,181 @@ +// Huffman Coding in C + +#include +#include + +#define MAX_TREE_HT 50 + +struct MinHNode { + char item; + unsigned freq; + struct MinHNode *left, *right; +}; + +struct MinHeap { + unsigned size; + unsigned capacity; + struct MinHNode **array; +}; + +// Create nodes +struct MinHNode *newNode(char item, unsigned freq) { + struct MinHNode *temp = (struct MinHNode *)malloc(sizeof(struct MinHNode)); + + temp->left = temp->right = NULL; + temp->item = item; + temp->freq = freq; + + return temp; +} + +// Create min heap +struct MinHeap *createMinH(unsigned capacity) { + struct MinHeap *minHeap = (struct MinHeap *)malloc(sizeof(struct MinHeap)); + + minHeap->size = 0; + + minHeap->capacity = capacity; + + minHeap->array = (struct MinHNode **)malloc(minHeap->capacity * sizeof(struct MinHNode *)); + return minHeap; +} + +// Function to swap +void swapMinHNode(struct MinHNode **a, struct MinHNode **b) { + struct MinHNode *t = *a; + *a = *b; + *b = t; +} + +// Heapify +void minHeapify(struct MinHeap *minHeap, int idx) { + int smallest = idx; + int left = 2 * idx + 1; + int right = 2 * idx + 2; + + if (left < minHeap->size && minHeap->array[left]->freq < minHeap->array[smallest]->freq) + smallest = left; + + if (right < minHeap->size && minHeap->array[right]->freq < minHeap->array[smallest]->freq) + smallest = right; + + if (smallest != idx) { + swapMinHNode(&minHeap->array[smallest], &minHeap->array[idx]); + minHeapify(minHeap, smallest); + } +} + +// Check if size if 1 +int checkSizeOne(struct MinHeap *minHeap) { + return (minHeap->size == 1); +} + +// Extract min +struct MinHNode *extractMin(struct MinHeap *minHeap) { + struct MinHNode *temp = minHeap->array[0]; + minHeap->array[0] = minHeap->array[minHeap->size - 1]; + + --minHeap->size; + minHeapify(minHeap, 0); + + return temp; +} + +// Insertion function +void insertMinHeap(struct MinHeap *minHeap, struct MinHNode *minHeapNode) { + ++minHeap->size; + int i = minHeap->size - 1; + + while (i && minHeapNode->freq < minHeap->array[(i - 1) / 2]->freq) { + minHeap->array[i] = minHeap->array[(i - 1) / 2]; + i = (i - 1) / 2; + } + minHeap->array[i] = minHeapNode; +} + +void buildMinHeap(struct MinHeap *minHeap) { + int n = minHeap->size - 1; + int i; + + for (i = (n - 1) / 2; i >= 0; --i) + minHeapify(minHeap, i); +} + +int isLeaf(struct MinHNode *root) { + return !(root->left) && !(root->right); +} + +struct MinHeap *createAndBuildMinHeap(char item[], int freq[], int size) { + struct MinHeap *minHeap = createMinH(size); + + for (int i = 0; i < size; ++i) + minHeap->array[i] = newNode(item[i], freq[i]); + + minHeap->size = size; + buildMinHeap(minHeap); + + return minHeap; +} + +struct MinHNode *buildHuffmanTree(char item[], int freq[], int size) { + struct MinHNode *left, *right, *top; + struct MinHeap *minHeap = createAndBuildMinHeap(item, freq, size); + + while (!checkSizeOne(minHeap)) { + left = extractMin(minHeap); + right = extractMin(minHeap); + + top = newNode('$', left->freq + right->freq); + + top->left = left; + top->right = right; + + insertMinHeap(minHeap, top); + } + return extractMin(minHeap); +} + +void printHCodes(struct MinHNode *root, int arr[], int top) { + if (root->left) { + arr[top] = 0; + printHCodes(root->left, arr, top + 1); + } + if (root->right) { + arr[top] = 1; + printHCodes(root->right, arr, top + 1); + } + if (isLeaf(root)) { + printf(" %c | ", root->item); + printArray(arr, top); + } +} + +// Wrapper function +void HuffmanCodes(char item[], int freq[], int size) { + struct MinHNode *root = buildHuffmanTree(item, freq, size); + + int arr[MAX_TREE_HT], top = 0; + + printHCodes(root, arr, top); +} + +// Print the array +void printArray(int arr[], int n) { + int i; + for (i = 0; i < n; ++i) + printf("%d", arr[i]); + + printf("\n"); +} + +int main() { + char arr[] = {'A', 'B', 'C', 'D'}; + int freq[] = {5, 1, 6, 3}; + + int size = sizeof(arr) / sizeof(arr[0]); + + printf(" Char | Huffman code "); + printf("\n--------------------\n"); + + HuffmanCodes(arr, freq, size); +} \ No newline at end of file diff --git a/rabin_karp_algorithm/Rabin.java b/rabin_karp_algorithm/Rabin.java new file mode 100644 index 0000000..36f0fa3 --- /dev/null +++ b/rabin_karp_algorithm/Rabin.java @@ -0,0 +1,68 @@ +public class Main { + // d is the number of characters in the input alphabet + public final static int d = 256; + + /* pat -> pattern + txt -> text + q -> A prime number + */ + static void search(String pat, String txt, int q) + { + int M = pat.length(); + int N = txt.length(); + int i, j; + int p = 0; // hash value for pattern + int t = 0; // hash value for txt + int h = 1; + + // The value of h would be "pow(d, M-1)%q" + for (i = 0; i < M - 1; i++) + h = (h * d) % q; + + // Calculate the hash value of pattern and first + // window of text + for (i = 0; i < M; i++) { + p = (d * p + pat.charAt(i)) % q; + t = (d * t + txt.charAt(i)) % q; + } + + // Slide the pattern over text one by one + for (i = 0; i <= N - M; i++) { + + // Check the hash values of current window of text + // and pattern. If the hash values match then only + // check for characters on by one + if (p == t) { + /* Check for characters one by one */ + for (j = 0; j < M; j++) { + if (txt.charAt(i + j) != pat.charAt(j)) + break; + } + + // if p == t and pat[0...M-1] = txt[i, i+1, ...i+M-1] + if (j == M) + System.out.println("Pattern found at index " + i); + } + + // Calculate hash value for next window of text: Remove + // leading digit, add trailing digit + if (i < N - M) { + t = (d * (t - txt.charAt(i) * h) + txt.charAt(i + M)) % q; + + // We might get negative value of t, converting it + // to positive + if (t < 0) + t = (t + q); + } + } + } + + /* Driver program to test above function */ + public static void main(String[] args) + { + String txt = "GEEKS FOR GEEKS"; + String pat = "GEEK"; + int q = 101; // A prime number + search(pat, txt, q); + } +}