From 817a2aa567866d3e20873d304f8447d5507f5193 Mon Sep 17 00:00:00 2001 From: Harshitha K Date: Sun, 10 Oct 2021 19:22:31 +0530 Subject: [PATCH 01/55] BubbleSort.java --- Bubble Sort/BubbleSort.java | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) create mode 100644 Bubble Sort/BubbleSort.java diff --git a/Bubble Sort/BubbleSort.java b/Bubble Sort/BubbleSort.java new file mode 100644 index 0000000..02e379a --- /dev/null +++ b/Bubble Sort/BubbleSort.java @@ -0,0 +1,35 @@ +class BubbleSort +{ + void bubbleSort(int arr[]) + { + int n = arr.length; + for (int i = 0; i < n-1; i++) + for (int j = 0; j < n-i-1; j++) + if (arr[j] > arr[j+1]) + { + // swap arr[j+1] and arr[j] + int temp = arr[j]; + arr[j] = arr[j+1]; + arr[j+1] = temp; + } + } + + /* Prints the array */ + void printArray(int arr[]) + { + int n = arr.length; + for (int i=0; i Date: Sun, 10 Oct 2021 19:24:58 +0530 Subject: [PATCH 02/55] HeapSort.cs --- Heapsort/HeapSort.cs | 44 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) create mode 100644 Heapsort/HeapSort.cs diff --git a/Heapsort/HeapSort.cs b/Heapsort/HeapSort.cs new file mode 100644 index 0000000..ea350d9 --- /dev/null +++ b/Heapsort/HeapSort.cs @@ -0,0 +1,44 @@ +using System; +namespace HeapSortDemo { + public class example { + static void heapSort(int[] arr, int n) { + for (int i = n / 2 - 1; i >= 0; i--) + heapify(arr, n, i); + for (int i = n-1; i>=0; i--) { + int temp = arr[0]; + arr[0] = arr[i]; + arr[i] = temp; + heapify(arr, i, 0); + } + } + static void heapify(int[] arr, int n, int i) { + int largest = i; + int left = 2*i + 1; + int right = 2*i + 2; + if (left < n && arr[left] > arr[largest]) + largest = left; + if (right < n && arr[right] > arr[largest]) + largest = right; + if (largest != i) { + int swap = arr[i]; + arr[i] = arr[largest]; + arr[largest] = swap; + heapify(arr, n, largest); + } + } + public static void Main() { + int[] arr = {55, 25, 89, 34, 12, 19, 78, 95, 1, 100}; + int n = 10, i; + Console.WriteLine("Heap Sort"); + Console.Write("Initial array is: "); + for (i = 0; i < n; i++) { + Console.Write(arr[i] + " "); + } + heapSort(arr, 10); + Console.Write("\nSorted Array is: "); + for (i = 0; i < n; i++) { + Console.Write(arr[i] + " "); + } + } + } +} From 949c3cb450f1b63d75cad1c3a840ae337d65646b Mon Sep 17 00:00:00 2001 From: Harshitha K Date: Sun, 10 Oct 2021 19:27:14 +0530 Subject: [PATCH 03/55] Create AStar.cpp --- A star algorithm/AStar.cpp | 636 +++++++++++++++++++++++++++++++++++++ 1 file changed, 636 insertions(+) create mode 100644 A star algorithm/AStar.cpp diff --git a/A star algorithm/AStar.cpp b/A star algorithm/AStar.cpp new file mode 100644 index 0000000..fedf945 --- /dev/null +++ b/A star algorithm/AStar.cpp @@ -0,0 +1,636 @@ +#include +using namespace std; + +#define ROW 9 +#define COL 10 + +// Creating a shortcut for int, int pair type +typedef pair Pair; + +// Creating a shortcut for pair> type +typedef pair > pPair; + +// A structure to hold the necessary parameters +struct cell { + // Row and Column index of its parent + // Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 + int parent_i, parent_j; + // f = g + h + double f, g, h; +}; + +// A Utility Function to check whether given cell (row, col) +// is a valid cell or not. +bool isValid(int row, int col) +{ + // Returns true if row number and column number + // is in range + return (row >= 0) && (row < ROW) && (col >= 0) + && (col < COL); +} + +// A Utility Function to check whether the given cell is +// blocked or not +bool isUnBlocked(int grid[][COL], int row, int col) +{ + // Returns true if the cell is not blocked else false + if (grid[row][col] == 1) + return (true); + else + return (false); +} + +// A Utility Function to check whether destination cell has +// been reached or not +bool isDestination(int row, int col, Pair dest) +{ + if (row == dest.first && col == dest.second) + return (true); + else + return (false); +} + +// A Utility Function to calculate the 'h' heuristics. +double calculateHValue(int row, int col, Pair dest) +{ + // Return using the distance formula + return ((double)sqrt( + (row - dest.first) * (row - dest.first) + + (col - dest.second) * (col - dest.second))); +} + +// A Utility Function to trace the path from the source +// to destination +void tracePath(cell cellDetails[][COL], Pair dest) +{ + printf("\nThe Path is "); + int row = dest.first; + int col = dest.second; + + stack Path; + + while (!(cellDetails[row][col].parent_i == row + && cellDetails[row][col].parent_j == col)) { + Path.push(make_pair(row, col)); + int temp_row = cellDetails[row][col].parent_i; + int temp_col = cellDetails[row][col].parent_j; + row = temp_row; + col = temp_col; + } + + Path.push(make_pair(row, col)); + while (!Path.empty()) { + pair p = Path.top(); + Path.pop(); + printf("-> (%d,%d) ", p.first, p.second); + } + + return; +} + +// A Function to find the shortest path between +// a given source cell to a destination cell according +// to A* Search Algorithm +void aStarSearch(int grid[][COL], Pair src, Pair dest) +{ + // If the source is out of range + if (isValid(src.first, src.second) == false) { + printf("Source is invalid\n"); + return; + } + + // If the destination is out of range + if (isValid(dest.first, dest.second) == false) { + printf("Destination is invalid\n"); + return; + } + + // Either the source or the destination is blocked + if (isUnBlocked(grid, src.first, src.second) == false + || isUnBlocked(grid, dest.first, dest.second) + == false) { + printf("Source or the destination is blocked\n"); + return; + } + + // If the destination cell is the same as source cell + if (isDestination(src.first, src.second, dest) + == true) { + printf("We are already at the destination\n"); + return; + } + + // Create a closed list and initialise it to false which + // means that no cell has been included yet This closed + // list is implemented as a boolean 2D array + bool closedList[ROW][COL]; + memset(closedList, false, sizeof(closedList)); + + // Declare a 2D array of structure to hold the details + // of that cell + cell cellDetails[ROW][COL]; + + int i, j; + + for (i = 0; i < ROW; i++) { + for (j = 0; j < COL; j++) { + cellDetails[i][j].f = FLT_MAX; + cellDetails[i][j].g = FLT_MAX; + cellDetails[i][j].h = FLT_MAX; + cellDetails[i][j].parent_i = -1; + cellDetails[i][j].parent_j = -1; + } + } + + // Initialising the parameters of the starting node + i = src.first, j = src.second; + cellDetails[i][j].f = 0.0; + cellDetails[i][j].g = 0.0; + cellDetails[i][j].h = 0.0; + cellDetails[i][j].parent_i = i; + cellDetails[i][j].parent_j = j; + + /* + Create an open list having information as- + > + where f = g + h, + and i, j are the row and column index of that cell + Note that 0 <= i <= ROW-1 & 0 <= j <= COL-1 + This open list is implemented as a set of pair of + pair.*/ + set openList; + + // Put the starting cell on the open list and set its + // 'f' as 0 + openList.insert(make_pair(0.0, make_pair(i, j))); + + // We set this boolean value as false as initially + // the destination is not reached. + bool foundDest = false; + + while (!openList.empty()) { + pPair p = *openList.begin(); + + // Remove this vertex from the open list + openList.erase(openList.begin()); + + // Add this vertex to the closed list + i = p.second.first; + j = p.second.second; + closedList[i][j] = true; + + /* + Generating all the 8 successor of this cell + + N.W N N.E + \ | / + \ | / + W----Cell----E + / | \ + / | \ + S.W S S.E + + Cell-->Popped Cell (i, j) + N --> North (i-1, j) + S --> South (i+1, j) + E --> East (i, j+1) + W --> West (i, j-1) + N.E--> North-East (i-1, j+1) + N.W--> North-West (i-1, j-1) + S.E--> South-East (i+1, j+1) + S.W--> South-West (i+1, j-1)*/ + + // To store the 'g', 'h' and 'f' of the 8 successors + double gNew, hNew, fNew; + + //----------- 1st Successor (North) ------------ + + // Only process this cell if this is a valid one + if (isValid(i - 1, j) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i - 1, j, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i - 1][j].parent_i = i; + cellDetails[i - 1][j].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i - 1][j] == false + && isUnBlocked(grid, i - 1, j) + == true) { + gNew = cellDetails[i][j].g + 1.0; + hNew = calculateHValue(i - 1, j, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i - 1][j].f == FLT_MAX + || cellDetails[i - 1][j].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i - 1, j))); + + // Update the details of this cell + cellDetails[i - 1][j].f = fNew; + cellDetails[i - 1][j].g = gNew; + cellDetails[i - 1][j].h = hNew; + cellDetails[i - 1][j].parent_i = i; + cellDetails[i - 1][j].parent_j = j; + } + } + } + + //----------- 2nd Successor (South) ------------ + + // Only process this cell if this is a valid one + if (isValid(i + 1, j) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i + 1, j, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i + 1][j].parent_i = i; + cellDetails[i + 1][j].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i + 1][j] == false + && isUnBlocked(grid, i + 1, j) + == true) { + gNew = cellDetails[i][j].g + 1.0; + hNew = calculateHValue(i + 1, j, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i + 1][j].f == FLT_MAX + || cellDetails[i + 1][j].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i + 1, j))); + // Update the details of this cell + cellDetails[i + 1][j].f = fNew; + cellDetails[i + 1][j].g = gNew; + cellDetails[i + 1][j].h = hNew; + cellDetails[i + 1][j].parent_i = i; + cellDetails[i + 1][j].parent_j = j; + } + } + } + + //----------- 3rd Successor (East) ------------ + + // Only process this cell if this is a valid one + if (isValid(i, j + 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i, j + 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i][j + 1].parent_i = i; + cellDetails[i][j + 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i][j + 1] == false + && isUnBlocked(grid, i, j + 1) + == true) { + gNew = cellDetails[i][j].g + 1.0; + hNew = calculateHValue(i, j + 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i][j + 1].f == FLT_MAX + || cellDetails[i][j + 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i, j + 1))); + + // Update the details of this cell + cellDetails[i][j + 1].f = fNew; + cellDetails[i][j + 1].g = gNew; + cellDetails[i][j + 1].h = hNew; + cellDetails[i][j + 1].parent_i = i; + cellDetails[i][j + 1].parent_j = j; + } + } + } + + //----------- 4th Successor (West) ------------ + + // Only process this cell if this is a valid one + if (isValid(i, j - 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i, j - 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i][j - 1].parent_i = i; + cellDetails[i][j - 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i][j - 1] == false + && isUnBlocked(grid, i, j - 1) + == true) { + gNew = cellDetails[i][j].g + 1.0; + hNew = calculateHValue(i, j - 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i][j - 1].f == FLT_MAX + || cellDetails[i][j - 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i, j - 1))); + + // Update the details of this cell + cellDetails[i][j - 1].f = fNew; + cellDetails[i][j - 1].g = gNew; + cellDetails[i][j - 1].h = hNew; + cellDetails[i][j - 1].parent_i = i; + cellDetails[i][j - 1].parent_j = j; + } + } + } + + //----------- 5th Successor (North-East) + //------------ + + // Only process this cell if this is a valid one + if (isValid(i - 1, j + 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i - 1, j + 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i - 1][j + 1].parent_i = i; + cellDetails[i - 1][j + 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i - 1][j + 1] == false + && isUnBlocked(grid, i - 1, j + 1) + == true) { + gNew = cellDetails[i][j].g + 1.414; + hNew = calculateHValue(i - 1, j + 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i - 1][j + 1].f == FLT_MAX + || cellDetails[i - 1][j + 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i - 1, j + 1))); + + // Update the details of this cell + cellDetails[i - 1][j + 1].f = fNew; + cellDetails[i - 1][j + 1].g = gNew; + cellDetails[i - 1][j + 1].h = hNew; + cellDetails[i - 1][j + 1].parent_i = i; + cellDetails[i - 1][j + 1].parent_j = j; + } + } + } + + //----------- 6th Successor (North-West) + //------------ + + // Only process this cell if this is a valid one + if (isValid(i - 1, j - 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i - 1, j - 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i - 1][j - 1].parent_i = i; + cellDetails[i - 1][j - 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i - 1][j - 1] == false + && isUnBlocked(grid, i - 1, j - 1) + == true) { + gNew = cellDetails[i][j].g + 1.414; + hNew = calculateHValue(i - 1, j - 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i - 1][j - 1].f == FLT_MAX + || cellDetails[i - 1][j - 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i - 1, j - 1))); + // Update the details of this cell + cellDetails[i - 1][j - 1].f = fNew; + cellDetails[i - 1][j - 1].g = gNew; + cellDetails[i - 1][j - 1].h = hNew; + cellDetails[i - 1][j - 1].parent_i = i; + cellDetails[i - 1][j - 1].parent_j = j; + } + } + } + + //----------- 7th Successor (South-East) + //------------ + + // Only process this cell if this is a valid one + if (isValid(i + 1, j + 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i + 1, j + 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i + 1][j + 1].parent_i = i; + cellDetails[i + 1][j + 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i + 1][j + 1] == false + && isUnBlocked(grid, i + 1, j + 1) + == true) { + gNew = cellDetails[i][j].g + 1.414; + hNew = calculateHValue(i + 1, j + 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i + 1][j + 1].f == FLT_MAX + || cellDetails[i + 1][j + 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i + 1, j + 1))); + + // Update the details of this cell + cellDetails[i + 1][j + 1].f = fNew; + cellDetails[i + 1][j + 1].g = gNew; + cellDetails[i + 1][j + 1].h = hNew; + cellDetails[i + 1][j + 1].parent_i = i; + cellDetails[i + 1][j + 1].parent_j = j; + } + } + } + + //----------- 8th Successor (South-West) + //------------ + + // Only process this cell if this is a valid one + if (isValid(i + 1, j - 1) == true) { + // If the destination cell is the same as the + // current successor + if (isDestination(i + 1, j - 1, dest) == true) { + // Set the Parent of the destination cell + cellDetails[i + 1][j - 1].parent_i = i; + cellDetails[i + 1][j - 1].parent_j = j; + printf("The destination cell is found\n"); + tracePath(cellDetails, dest); + foundDest = true; + return; + } + + // If the successor is already on the closed + // list or if it is blocked, then ignore it. + // Else do the following + else if (closedList[i + 1][j - 1] == false + && isUnBlocked(grid, i + 1, j - 1) + == true) { + gNew = cellDetails[i][j].g + 1.414; + hNew = calculateHValue(i + 1, j - 1, dest); + fNew = gNew + hNew; + + // If it isn’t on the open list, add it to + // the open list. Make the current square + // the parent of this square. Record the + // f, g, and h costs of the square cell + // OR + // If it is on the open list already, check + // to see if this path to that square is + // better, using 'f' cost as the measure. + if (cellDetails[i + 1][j - 1].f == FLT_MAX + || cellDetails[i + 1][j - 1].f > fNew) { + openList.insert(make_pair( + fNew, make_pair(i + 1, j - 1))); + + // Update the details of this cell + cellDetails[i + 1][j - 1].f = fNew; + cellDetails[i + 1][j - 1].g = gNew; + cellDetails[i + 1][j - 1].h = hNew; + cellDetails[i + 1][j - 1].parent_i = i; + cellDetails[i + 1][j - 1].parent_j = j; + } + } + } + } + + // When the destination cell is not found and the open + // list is empty, then we conclude that we failed to + // reach the destination cell. This may happen when the + // there is no way to destination cell (due to + // blockages) + if (foundDest == false) + printf("Failed to find the Destination Cell\n"); + + return; +} + +// Driver program to test above function +int main() +{ + /* Description of the Grid- + 1--> The cell is not blocked + 0--> The cell is blocked */ + int grid[ROW][COL] + = { { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, + { 1, 1, 1, 0, 1, 1, 1, 0, 1, 1 }, + { 1, 1, 1, 0, 1, 1, 0, 1, 0, 1 }, + { 0, 0, 1, 0, 1, 0, 0, 0, 0, 1 }, + { 1, 1, 1, 0, 1, 1, 1, 0, 1, 0 }, + { 1, 0, 1, 1, 1, 1, 0, 1, 0, 0 }, + { 1, 0, 0, 0, 0, 1, 0, 0, 0, 1 }, + { 1, 0, 1, 1, 1, 1, 0, 1, 1, 1 }, + { 1, 1, 1, 0, 0, 0, 1, 0, 0, 1 } }; + + // Source is the left-most bottom-most corner + Pair src = make_pair(8, 0); + + // Destination is the left-most top-most corner + Pair dest = make_pair(0, 0); + + aStarSearch(grid, src, dest); + + return (0); +} From 28f87f509f5b268ef34a64f26378aaa0e3688702 Mon Sep 17 00:00:00 2001 From: Harshitha K Date: Sun, 10 Oct 2021 19:29:46 +0530 Subject: [PATCH 04/55] kmp.java --- KMP Algorithm/kmp.java | 81 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 KMP Algorithm/kmp.java diff --git a/KMP Algorithm/kmp.java b/KMP Algorithm/kmp.java new file mode 100644 index 0000000..6756b46 --- /dev/null +++ b/KMP Algorithm/kmp.java @@ -0,0 +1,81 @@ +class KMP_String_Matching { + void KMPSearch(String pat, String txt) + { + int M = pat.length(); + int N = txt.length(); + + // create lps[] that will hold the longest + // prefix suffix values for pattern + int lps[] = new int[M]; + int j = 0; // index for pat[] + + // Preprocess the pattern (calculate lps[] + // array) + computeLPSArray(pat, M, lps); + + int i = 0; // index for txt[] + while (i < N) { + if (pat.charAt(j) == txt.charAt(i)) { + j++; + i++; + } + if (j == M) { + System.out.println("Found pattern " + + "at index " + (i - j)); + j = lps[j - 1]; + } + + // mismatch after j matches + else if (i < N && pat.charAt(j) != txt.charAt(i)) { + // Do not match lps[0..lps[j-1]] characters, + // they will match anyway + if (j != 0) + j = lps[j - 1]; + else + i = i + 1; + } + } + } + + void computeLPSArray(String pat, int M, int lps[]) + { + // length of the previous longest prefix suffix + int len = 0; + int i = 1; + lps[0] = 0; // lps[0] is always 0 + + // the loop calculates lps[i] for i = 1 to M-1 + while (i < M) { + if (pat.charAt(i) == pat.charAt(len)) { + len++; + lps[i] = len; + i++; + } + else // (pat[i] != pat[len]) + { + // This is tricky. Consider the example. + // AAACAAAA and i = 7. The idea is similar + // to search step. + if (len != 0) { + len = lps[len - 1]; + + // Also, note that we do not increment + // i here + } + else // if (len == 0) + { + lps[i] = len; + i++; + } + } + } + } + + // Driver program to test above function + public static void main(String args[]) + { + String txt = "ABABDABACDABABCABAB"; + String pat = "ABABCABAB"; + new KMP_String_Matching().KMPSearch(pat, txt); + } +} From 43d20ef9ed338d8a4ac57671cd7f117d89b54604 Mon Sep 17 00:00:00 2001 From: DeathRaven1051 <67112322+DeathRaven1051@users.noreply.github.com> Date: Sun, 10 Oct 2021 20:02:22 +0530 Subject: [PATCH 05/55] Create KMP_Algo.py A python algo program based upon KMP Algorithm --- KMP Algorithm/KMP_Algo.py | 58 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 KMP Algorithm/KMP_Algo.py diff --git a/KMP Algorithm/KMP_Algo.py b/KMP Algorithm/KMP_Algo.py new file mode 100644 index 0000000..1c08950 --- /dev/null +++ b/KMP Algorithm/KMP_Algo.py @@ -0,0 +1,58 @@ +def kmpAlgo(patt, recurr): + x = len(patt) + y = len(recurr) + + + lps = [0]*x + j = 0 + + + computeLPSArray(patt, x, lps) + + i = 0 + while i < y: + if patt[j] == recurr[i]: + i += 1 + j += 1 + + if j == x: + print ("Found pattern at index " + str(i-j)) + j = lps[j-1] + + + elif i < y and patt[j] != recurr[i]: + x + if j != 0: + j = lps[j-1] + else: + i += 1 + +def computeLPSArray(patt, x, lps): + len = 0 + + lps[0] + i = 1 + + + while i < x: + if patt[i]== patt[len]: + len += 1 + lps[i] = len + i += 1 + else: + + if len != 0: + len = lps[len-1] + + + else: + lps[i] = 0 + i += 1 + + + + + +kmpAlgo(recurr = input("Enter pattern "), patt = input("Enter Reccuring pattern ")) + + From 410f1fe377b6cee4d252d4922f1cc518b1c5b60f Mon Sep 17 00:00:00 2001 From: DeathRaven1051 <67112322+DeathRaven1051@users.noreply.github.com> Date: Sun, 10 Oct 2021 20:20:01 +0530 Subject: [PATCH 06/55] Add files via upload --- Insertion Sort/InsertionSort.py | 22 ++++++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 Insertion Sort/InsertionSort.py diff --git a/Insertion Sort/InsertionSort.py b/Insertion Sort/InsertionSort.py new file mode 100644 index 0000000..b5751b4 --- /dev/null +++ b/Insertion Sort/InsertionSort.py @@ -0,0 +1,22 @@ +def InsertionSort(arr): + + for i in range(1, len(arr)): + + key = arr[i] + + j = i-1 + while j >=0 and key < arr[j] : + arr[j+1] = arr[j] + j -= 1 + arr[j+1] = key + + + +arr = [112, 1, 12213,44, 44] + +InsertionSort(arr) +print ("Sorted Array: ") +for i in range(len(arr)): + print ("%d" %arr[i]) + + From 17e796f350ca42b548e9c7a86fb58c7e9614e298 Mon Sep 17 00:00:00 2001 From: chakeson <80765479+chakeson@users.noreply.github.com> Date: Tue, 12 Oct 2021 03:04:00 +0200 Subject: [PATCH 07/55] Added sdbm hashing algorithm. --- sdbm hash/sdbm.py | 15 +++++++++++++++ 1 file changed, 15 insertions(+) create mode 100644 sdbm hash/sdbm.py diff --git a/sdbm hash/sdbm.py b/sdbm hash/sdbm.py new file mode 100644 index 0000000..d4ecd1c --- /dev/null +++ b/sdbm hash/sdbm.py @@ -0,0 +1,15 @@ +''' +Old database hashfunction. +Source: +https://api.riot-os.org/group__sys__hashes__sdbm.html +http://www.cse.yorku.ca/~oz/hash.html +Docs for ord: https://docs.python.org/3/library/functions.html#ord +Returns the unicode character of a char. +''' + + +def sdbm(input_plain_text): + hash_output = 0 + for char in input_plain_text: + hash_output = ord(char) + (hash_output << 6) + (hash_output << 16) - hash_output + return hash_output \ No newline at end of file From 3dcdfc3b8f9eed27be5154b6abc33bfe225465d2 Mon Sep 17 00:00:00 2001 From: aman Date: Tue, 12 Oct 2021 12:18:07 +0530 Subject: [PATCH 08/55] Insertion sort in cpp added --- Insertion Sort/insertionsort.cpp | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Insertion Sort/insertionsort.cpp diff --git a/Insertion Sort/insertionsort.cpp b/Insertion Sort/insertionsort.cpp new file mode 100644 index 0000000..4743f61 --- /dev/null +++ b/Insertion Sort/insertionsort.cpp @@ -0,0 +1,30 @@ +#include +using namespace std; + +int main() +{ + int n; + cin>>n; + cout<<'\n'; + int *a=new int[n]; + for(int i=0;i<=n-1;i++){ + cin>>a[i]; + } + + + for(int i=1;i<=n-1;i++){ + int j=i-1; + int temp =a[i]; + while(j>=0&&a[j]>temp){ + a[j+1]=a[j]; + j--; + } + a[j+1]=temp; + + } + + for(int i=0;i<=n-1;i++){ + cout<< a[i]; + } + return 0; +} \ No newline at end of file From df7c4c06ccbab7622f731b9e441e015e78a2ea12 Mon Sep 17 00:00:00 2001 From: DeathRaven1051 <67112322+DeathRaven1051@users.noreply.github.com> Date: Fri, 15 Oct 2021 15:35:23 +0530 Subject: [PATCH 09/55] Add files via upload --- Armstrong Number/Amrstrong.py | 12 ++++++++++++ 1 file changed, 12 insertions(+) create mode 100644 Armstrong Number/Amrstrong.py diff --git a/Armstrong Number/Amrstrong.py b/Armstrong Number/Amrstrong.py new file mode 100644 index 0000000..137ae54 --- /dev/null +++ b/Armstrong Number/Amrstrong.py @@ -0,0 +1,12 @@ +sum=0 +def check_ArmstrongNumber(num): + global sum + if (num!=0): + sum+=pow(num%10,3) + check_ArmstrongNumber(num//10) + return sum +num=int(input("Enter a number:")) +if (check_ArmstrongNumber(num) == num): + print("It's an Armstrong Number.") +else: + print("Not an Armstrong Number.") \ No newline at end of file From e01f7a25dc30d36a006b421de8e97c1409b99f88 Mon Sep 17 00:00:00 2001 From: HUMANORE Date: Fri, 15 Oct 2021 19:36:10 +0530 Subject: [PATCH 10/55] Create rabin-karp_algorithm.py Please accept pr!! --- rabin_karp_algorithm/rabin-karp_algorithm.py | 69 ++++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 rabin_karp_algorithm/rabin-karp_algorithm.py diff --git a/rabin_karp_algorithm/rabin-karp_algorithm.py b/rabin_karp_algorithm/rabin-karp_algorithm.py new file mode 100644 index 0000000..9aabe6e --- /dev/null +++ b/rabin_karp_algorithm/rabin-karp_algorithm.py @@ -0,0 +1,69 @@ +d = 265 + +# pat -> pattern +# txt -> text +# prime -> A prime number + + +def search(pat, txt, prime): + + M = len(pat) + + N = len(txt) + i = 0 + j = 0 + p = 0 + t = 0 + + h = 1 + + for i in xrange(M-1): + + h = (h*d)%prime + + + for i in xrange(M): + + p = (d*p + ord(pat[i]))%prime + + t = (d*t + ord(txt[i]))%prime + + + for i in xrange(N-M+1): + + if p==t: + + for j in xrange(M): + + if txt[i+j] != pat[j]: + + break + + else: j+=1 + + if j==M: + + print "Pattern found at index " + str(i) + + + if i < N-M: + + t = (d*(t-ord(txt[i])*h) + ord(txt[i+M]))%prime + + + if t < 0: + + t = t+prime + + + +txt = "I AM CHAITANYA" + +pat = "AM" + + + +prime= 101 + +# Function Call +search(pat,txt, prime) From 7f971dabcc0d4ec189de48fb6e72c4002f044a14 Mon Sep 17 00:00:00 2001 From: Harsh <57654076+harshkumar05@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:01:40 +0530 Subject: [PATCH 11/55] Astar in java fully functional and optimized code --- A star algorithm/Astar.java | 141 ++++++++++++++++++++++++++++++++++++ 1 file changed, 141 insertions(+) create mode 100644 A star algorithm/Astar.java diff --git a/A star algorithm/Astar.java b/A star algorithm/Astar.java new file mode 100644 index 0000000..ca7dcfd --- /dev/null +++ b/A star algorithm/Astar.java @@ -0,0 +1,141 @@ +public class Node implements Comparable { + // Id for readability of result purposes + private static int idCounter = 0; + public int id; + + // Parent in the path + public Node parent = null; + + public List neighbors; + + // Evaluation functions + public double f = Double.MAX_VALUE; + public double g = Double.MAX_VALUE; + // Hardcoded heuristic + public double h; + + Node(double h){ + this.h = h; + this.id = idCounter++; + this.neighbors = new ArrayList<>(); + } + + @Override + public int compareTo(Node n) { + return Double.compare(this.f, n.f); + } + + public static class Edge { + Edge(int weight, Node node){ + this.weight = weight; + this.node = node; + } + + public int weight; + public Node node; + } + + public void addBranch(int weight, Node node){ + Edge newEdge = new Edge(weight, node); + neighbors.add(newEdge); + } + + public double calculateHeuristic(Node target){ + return this.h; + } +} + + + +public static Node aStar(Node start, Node target){ + PriorityQueue closedList = new PriorityQueue<>(); + PriorityQueue openList = new PriorityQueue<>(); + + start.f = start.g + start.calculateHeuristic(target); + openList.add(start); + + while(!openList.isEmpty()){ + Node n = openList.peek(); + if(n == target){ + return n; + } + + for(Node.Edge edge : n.neighbors){ + Node m = edge.node; + double totalWeight = n.g + edge.weight; + + if(!openList.contains(m) && !closedList.contains(m)){ + m.parent = n; + m.g = totalWeight; + m.f = m.g + m.calculateHeuristic(target); + openList.add(m); + } else { + if(totalWeight < m.g){ + m.parent = n; + m.g = totalWeight; + m.f = m.g + m.calculateHeuristic(target); + + if(closedList.contains(m)){ + closedList.remove(m); + openList.add(m); + } + } + } + } + + openList.remove(n); + closedList.add(n); + } + return null; +} + +public static void printPath(Node target){ + Node n = target; + + if(n==null) + return; + + List ids = new ArrayList<>(); + + while(n.parent != null){ + ids.add(n.id); + n = n.parent; + } + ids.add(n.id); + Collections.reverse(ids); + + for(int id : ids){ + System.out.print(id + " "); + } + System.out.println(""); +} + + +public static void main(String[] args) { + Node head = new Node(3); + head.g = 0; + + Node n1 = new Node(2); + Node n2 = new Node(2); + Node n3 = new Node(2); + + head.addBranch(1, n1); + head.addBranch(5, n2); + head.addBranch(2, n3); + n3.addBranch(1, n2); + + Node n4 = new Node(1); + Node n5 = new Node(1); + Node target = new Node(0); + + n1.addBranch(7, n4); + n2.addBranch(4, n5); + n3.addBranch(6, n4); + + n4.addBranch(3, target); + n5.addBranch(1, n4); + n5.addBranch(3, target); + + Node res = aStar(head, target); + printPath(res); +} From d5d1b257afb304ecb102ab915fdd3e2f732e1599 Mon Sep 17 00:00:00 2001 From: Harsh <57654076+harshkumar05@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:07:33 +0530 Subject: [PATCH 12/55] bellmanford // TC = O(T * N), SC = O(N), T-> length of times // Using Bellman-Ford to find shortest paths from node --- Bellman Ford algorithm/bellmanFord.java | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) create mode 100644 Bellman Ford algorithm/bellmanFord.java diff --git a/Bellman Ford algorithm/bellmanFord.java b/Bellman Ford algorithm/bellmanFord.java new file mode 100644 index 0000000..3320d87 --- /dev/null +++ b/Bellman Ford algorithm/bellmanFord.java @@ -0,0 +1,17 @@ +class Solution { + + public int networkDelayTime(int[][] times, int N, int K) { + int[] dist = new int[N]; + for (int i = 0; i < dist.length; i++) + dist[i] = (int)1e9; + dist[K - 1] = 0; + for (int i = 0; i < N; i++) { + for (int[] time: times) { + if (dist[time[0] - 1] + time[2] < dist[time[1] - 1]) { + dist[time[1] - 1] = dist[time[0] - 1] + time[2]; + } + } + } + if (Arrays.stream(dist).anyMatch(i -> i == (int)1e9)) return -1; + return Arrays.stream(dist).max().orElse(-1); + } From 7453ce55ce7016178a8fbe731ebad3e8381c6490 Mon Sep 17 00:00:00 2001 From: Harsh <57654076+harshkumar05@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:10:14 +0530 Subject: [PATCH 13/55] Create dijkstra.java optimized space time --- Dijkstra's Algorithm/dijkstra.java | 64 ++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Dijkstra's Algorithm/dijkstra.java diff --git a/Dijkstra's Algorithm/dijkstra.java b/Dijkstra's Algorithm/dijkstra.java new file mode 100644 index 0000000..75bbe3d --- /dev/null +++ b/Dijkstra's Algorithm/dijkstra.java @@ -0,0 +1,64 @@ +class Pair { + int city, cost; + + Pair(int city, int cost) { + this.city = city; + this.cost = cost; + } +} + +class City { + int city, distFromSrc, costFromSrc; + + City(int city, int distFromSrc, int cost) { + this.city = city; + this.distFromSrc = distFromSrc; + this.costFromSrc = cost; + } +} + +class Solution { + + public int findCheapestPrice(int n, int[][] flights, int src, int dst, int K) { + // DFS + if(n <= 0 || flights == null || flights.length == 0 || K < 0) + return -1; + + List> graph = new ArrayList<>(); + this.buildGraph(graph, n, flights); + + Queue pQueue = new PriorityQueue<>((City c1, City c2) -> c1.costFromSrc - c2.costFromSrc); + pQueue.offer(new City(src, 0, 0)); + + int totalCost = 0; + + while (!pQueue.isEmpty()) { + City top = pQueue.poll(); + + if (top.city == dst) { + return top.costFromSrc; + } + + if (top.distFromSrc > K) { + continue; + } + + List neighbors = graph.get(top.city); + for (Pair neighbor: neighbors) { + pQueue.offer(new City(neighbor.city, top.distFromSrc + 1, top.costFromSrc + neighbor.cost)); + } + } + + return -1; + } + + private void buildGraph(List> graph, int n, int[][] flights) { + for (int i = 0; i < n; i++) { + graph.add(new ArrayList<>()); + } + + for (int[] flight: flights) { + graph.get(flight[0]).add(new Pair(flight[1], flight[2])); + } + } +} From a3c9c8be921f706efc2ad9ba1996cb6fc5956d26 Mon Sep 17 00:00:00 2001 From: Harsh <57654076+harshkumar05@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:13:34 +0530 Subject: [PATCH 14/55] Heapsort Detailed Building a heap is nlogn. Each value is added as a leaf node, then it bubbles up the heap to its correct location. To turn a heap into a sorted array, remove the root (which is the current max value), replace it with a leaf node, then let the new root sink down to its correct location. This is also nlogn. edit: Thanks to RodneyShag for suggesting a significant optimization. Rather than iteratively adding nodes to a heap, we can merge smaller heaps until only one is left. This ends up being O(n) for building the heap. Improved code: O(n) build heap, O(nlogn) convert heap to sorted array --- Heapsort/hpsort.java | 64 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 Heapsort/hpsort.java diff --git a/Heapsort/hpsort.java b/Heapsort/hpsort.java new file mode 100644 index 0000000..4a03f6e --- /dev/null +++ b/Heapsort/hpsort.java @@ -0,0 +1,64 @@ +public static int[] heapSort(int[] nums) { + //build the heap + for(int i=nums.length-1;i>=0;i--) + //merge the 2 sub-heaps below i, by bubbling nums[i] down to the correct location + sink(nums,i,nums.length); + //turn it into a sorted list + for(int i=nums.length-1;i>0;i--){ + //remove the root, and put the last leaf at the root of the heap + int tmp = nums[i]; + nums[i]=nums[0]; + nums[0] = tmp; + //bubble the new root down to the correct location + sink(nums,0,i); + } + return nums; +} +static void sink(int[] nums, int start, int end){ + int val = nums[start]; + int i = start, next = 2*i+1; + while(nextnums[next]) + next++; + if(nums[next]<=val) + break; + nums[i]=nums[next]; + i=next; + next = 2*i+1; //2*i+1, 2*i+2 are the children of i + } + nums[i]=val; +} +Original code: O(nlogn) build heap + +public static int[] heapSort(int[] nums) { + //build the heap + for(int i=1;i0 && nums[next]0;i--){ + int val = nums[i]; + nums[i]=nums[0]; + + int j = 0, next = 1; + while(nextnums[next]) + next++; + if(nums[next]<=val) + break; + nums[j]=nums[next]; + j=next; + next = 2*j+1; //2*j+1, 2*j+2 are the children of j + } + nums[j]=val; + } + return nums; +} From 1ff0f527ec938d9aec5df83ff7c6873c8af16a24 Mon Sep 17 00:00:00 2001 From: Harsh <57654076+harshkumar05@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:17:21 +0530 Subject: [PATCH 15/55] jump game variation we have a Greedy Approach here then we will take the path 1+99+1 as we select local optimum from the beggining But if we take DP Approach then we start from back and find the cost of reaching end from that specific node. So when we reach the first node we will have two options 99+1 path 5+1 path Now we simply have to decide between (1+(99+1)) and (20+(5+1)) path --- Jump Search/jump.java | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 Jump Search/jump.java diff --git a/Jump Search/jump.java b/Jump Search/jump.java new file mode 100644 index 0000000..0e581e4 --- /dev/null +++ b/Jump Search/jump.java @@ -0,0 +1,19 @@ + bool canJump(vector& nums) { + int n = nums.size(); + vector jump(n,false); + jump[n-1]=true; + + for(int i=n-2;i>=0;i--) + { + for(int j=0;j<=nums[i] && i+j Date: Sat, 16 Oct 2021 00:31:50 +0530 Subject: [PATCH 16/55] Create KMP_1.java --- KMP Algorithm/KMP_1.java | 47 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 KMP Algorithm/KMP_1.java 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; +} From 5835f029a3ec3481ce61a3a319d9fadaa01e5795 Mon Sep 17 00:00:00 2001 From: Harsh Raj <49561994+harshraj21@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:34:48 +0530 Subject: [PATCH 17/55] Create MERGE_1.java --- MergeSort/MERGE_1.java | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 MergeSort/MERGE_1.java 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]; + } + } + + +} From bf698ba9c6244dd8299f7eb17c33c90ca313018f Mon Sep 17 00:00:00 2001 From: Harsh Raj <49561994+harshraj21@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:35:52 +0530 Subject: [PATCH 18/55] Create QuickSort.java --- QuickSort/QuickSort.java | 58 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 QuickSort/QuickSort.java 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(); + } +} From ad9cb447e944b916291009ecb0b254519c0b6af6 Mon Sep 17 00:00:00 2001 From: Harsh Raj <49561994+harshraj21@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:37:24 +0530 Subject: [PATCH 19/55] Create SelSort.java --- Selection sort/SelSort.java | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) create mode 100644 Selection sort/SelSort.java 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+" "); + } + } +} From 6ed74fad0090129fd52de6b05d4c5850f5120224 Mon Sep 17 00:00:00 2001 From: Harsh Raj <49561994+harshraj21@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:40:35 +0530 Subject: [PATCH 20/55] Create Rabin.java --- rabin_karp_algorithm/Rabin.java | 68 +++++++++++++++++++++++++++++++++ 1 file changed, 68 insertions(+) create mode 100644 rabin_karp_algorithm/Rabin.java 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); + } +} From 264f78094f26cf95b2b677dac775c72b50b9a190 Mon Sep 17 00:00:00 2001 From: Harsh Raj <49561994+harshraj21@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:41:29 +0530 Subject: [PATCH 21/55] Create Armstrong.java --- Armstrong Number/Armstrong.java | 49 +++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) create mode 100644 Armstrong Number/Armstrong.java diff --git a/Armstrong Number/Armstrong.java b/Armstrong Number/Armstrong.java new file mode 100644 index 0000000..a2e8f0d --- /dev/null +++ b/Armstrong Number/Armstrong.java @@ -0,0 +1,49 @@ +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+ ", "); +} +} From b6c0ae4af8685d4f837b460d30609af198e581a8 Mon Sep 17 00:00:00 2001 From: Harsh Raj <49561994+harshraj21@users.noreply.github.com> Date: Sat, 16 Oct 2021 00:43:25 +0530 Subject: [PATCH 22/55] Create jump.py --- Jump Search/jump.py | 46 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Jump Search/jump.py 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". From fde5789712b016716f5f101bb08bcf2b00e76c05 Mon Sep 17 00:00:00 2001 From: chakeson <80765479+chakeson@users.noreply.github.com> Date: Sat, 16 Oct 2021 02:11:01 +0200 Subject: [PATCH 23/55] Added adler32 hashing algorithm. --- adler32 hash/adler32.py | 18 ++++++++++++++++++ 1 file changed, 18 insertions(+) create mode 100644 adler32 hash/adler32.py 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 + + From 145748d079b24526f11bafac164da29a76fb33d9 Mon Sep 17 00:00:00 2001 From: kirtisingh3008 Date: Sat, 16 Oct 2021 12:07:24 +0530 Subject: [PATCH 24/55] Added minimum spanning tree --- MST/Kruskals.cpp | 84 ++++++++++++++++++++++++++++++++++++++++++++++++ MST/Prims.cpp | 71 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 155 insertions(+) create mode 100644 MST/Kruskals.cpp create mode 100644 MST/Prims.cpp 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 From bb019c7886b05d316b8ed8a42cb9e1766ed081a6 Mon Sep 17 00:00:00 2001 From: Caleb Felix Date: Sun, 17 Oct 2021 12:01:09 +0530 Subject: [PATCH 25/55] Add files via upload --- Linked LIst/reverse-a-inkedlist.js | 47 ++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Linked LIst/reverse-a-inkedlist.js 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 From 67f97b6cf6e89e82d58f35c0ddc30d50d9025e4f Mon Sep 17 00:00:00 2001 From: Anubhav Maheshwari <55053867+anubhavmaheshwari0805@users.noreply.github.com> Date: Tue, 19 Oct 2021 11:01:54 +0530 Subject: [PATCH 26/55] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 37f16dc..5549443 100644 --- a/README.md +++ b/README.md @@ -10,6 +10,6 @@ Help us make a deposit of algorithms. -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. From 05cd0cece2bbd11a79e456dfd7fd55ba1a3d1542 Mon Sep 17 00:00:00 2001 From: Anubhav Maheshwari <55053867+anubhavmaheshwari0805@users.noreply.github.com> Date: Tue, 19 Oct 2021 11:11:01 +0530 Subject: [PATCH 27/55] Update Armstrong.java --- Armstrong Number/Armstrong.java | 83 ++++++++++++++++----------------- 1 file changed, 39 insertions(+), 44 deletions(-) diff --git a/Armstrong Number/Armstrong.java b/Armstrong Number/Armstrong.java index a2e8f0d..204cd93 100644 --- a/Armstrong Number/Armstrong.java +++ b/Armstrong Number/Armstrong.java @@ -1,49 +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; +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+ ", "); -} +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+ ", "); + } } From 8b90c29ec2381492bd71e20c2ed85b90adf9dc75 Mon Sep 17 00:00:00 2001 From: Anubhav Maheshwari <55053867+anubhavmaheshwari0805@users.noreply.github.com> Date: Tue, 19 Oct 2021 11:20:31 +0530 Subject: [PATCH 28/55] Create Binary-Insertion-Sort.py --- .../Binary-Insertion-Sort.py | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) create mode 100644 Binary Insertion Sort/Binary-Insertion-Sort.py 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]) From f333c5b342caed844da8db346b5cea1ba395aedc Mon Sep 17 00:00:00 2001 From: Anubhav Maheshwari <55053867+anubhavmaheshwari0805@users.noreply.github.com> Date: Tue, 19 Oct 2021 11:51:38 +0530 Subject: [PATCH 29/55] Create Bucket-sort.cpp --- Bucket Sort/Bucket-sort.cpp | 46 +++++++++++++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 Bucket Sort/Bucket-sort.cpp 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; +} From 6ec6a9e80f33d85a112f330328b99aace2056897 Mon Sep 17 00:00:00 2001 From: SUNIT KUMAR SINGHA <72279547+sunitwiz89@users.noreply.github.com> Date: Tue, 19 Oct 2021 12:21:36 +0530 Subject: [PATCH 30/55] prims.py --- MST/prims.py | 37 +++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 MST/prims.py 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 From 9099cc8ad43ce01d4717c704add8d948080d156e Mon Sep 17 00:00:00 2001 From: chakeson <80765479+chakeson@users.noreply.github.com> Date: Tue, 19 Oct 2021 15:50:51 +0200 Subject: [PATCH 31/55] Added djb2 hashing algorithm --- djb2 hash/djb2.py | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) create mode 100644 djb2 hash/djb2.py 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 From 0864d522c84e4d5843c1544a0d8fcff6980b962b Mon Sep 17 00:00:00 2001 From: Caleb Felix Date: Wed, 20 Oct 2021 12:40:41 +0530 Subject: [PATCH 32/55] Create BubbleSort.js --- Bubble Sort/BubbleSort.js | 45 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 45 insertions(+) create mode 100644 Bubble Sort/BubbleSort.js 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); + + From a43b00292dcba218734048bd801c4b40703923a9 Mon Sep 17 00:00:00 2001 From: vivek-guda Date: Wed, 20 Oct 2021 14:42:41 +0530 Subject: [PATCH 33/55] added merge sort in cpp --- MergeSort/MergeSort.cpp | 62 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100755 MergeSort/MergeSort.cpp 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 From bb12375ee84bf3322dbc2dbf4d513c6dce61ee1e Mon Sep 17 00:00:00 2001 From: BugHunters-bug <91728280+BugHunters-bug@users.noreply.github.com> Date: Wed, 20 Oct 2021 14:59:56 +0530 Subject: [PATCH 34/55] Update README.md --- README.md | 1 + 1 file changed, 1 insertion(+) diff --git a/README.md b/README.md index 5549443..d4c09ce 100644 --- a/README.md +++ b/README.md @@ -3,6 +3,7 @@ Help us make a deposit of algorithms. #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.
From 9060c1abcc2816a5598db31f3bf11a13acc2a8fb Mon Sep 17 00:00:00 2001 From: BugHunters-bug <91728280+BugHunters-bug@users.noreply.github.com> Date: Wed, 20 Oct 2021 15:01:01 +0530 Subject: [PATCH 35/55] Update README.md --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index d4c09ce..949a3ce 100644 --- a/README.md +++ b/README.md @@ -3,7 +3,7 @@ Help us make a deposit of algorithms. #Rules to Contribute- --Check the issues section for new issues. +-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.
From b3a1b6a5ff51fc54c680b44562161db1948fbc1c Mon Sep 17 00:00:00 2001 From: JuniorS6 <92072877+JuniorS6@users.noreply.github.com> Date: Wed, 20 Oct 2021 18:05:57 +0530 Subject: [PATCH 36/55] Update README.md --- README.md | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index 949a3ce..503bff6 100644 --- a/README.md +++ b/README.md @@ -1,15 +1,18 @@ # 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. - +# Contributors + + + + If you need the PR for HacktoberFest 2021, please comment it and let us know. From 7fd2aa1fa5d4ae562470f13127c4e7c91e1c72ea Mon Sep 17 00:00:00 2001 From: Tejugowda1005 Date: Wed, 20 Oct 2021 23:55:03 +0530 Subject: [PATCH 37/55] Added fibonacci series cpp --- Fibonacci series/fibonacci.cpp | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) create mode 100644 Fibonacci series/fibonacci.cpp 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< Date: Thu, 21 Oct 2021 14:48:10 +0530 Subject: [PATCH 38/55] update readme readme updated --- README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/README.md b/README.md index 503bff6..c92c462 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ Help us make a deposit of algorithms. -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 From 39e426476e2376cce059fa8ebf95464cab3850fc Mon Sep 17 00:00:00 2001 From: Chayanin Kongsareekul <57552210+Aphrodicez@users.noreply.github.com> Date: Thu, 21 Oct 2021 18:22:42 +0700 Subject: [PATCH 39/55] Create Binary_Indexed_Tree.cpp --- .../Binary_Indexed_Tree.cpp | 50 +++++++++++++++++++ 1 file changed, 50 insertions(+) create mode 100644 Data Structure/Binary Indexed Tree ( Fenwick Tree )/Binary_Indexed_Tree.cpp 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; +} From ab24b1ec4c4dd8b5d27fe8d79abaf671c8d4b966 Mon Sep 17 00:00:00 2001 From: Sneha438 Date: Thu, 21 Oct 2021 22:25:22 +0530 Subject: [PATCH 40/55] Added Radix sort cpp --- Radix sort/Radix_sort.cpp.txt | 47 +++++++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) create mode 100644 Radix sort/Radix_sort.cpp.txt diff --git a/Radix sort/Radix_sort.cpp.txt b/Radix sort/Radix_sort.cpp.txt new file mode 100644 index 0000000..93ebc60 --- /dev/null +++ b/Radix sort/Radix_sort.cpp.txt @@ -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); +} \ No newline at end of file From 612bc46067d73b1dc96845cabd5af08189a988dc Mon Sep 17 00:00:00 2001 From: Caleb Felix Date: Fri, 22 Oct 2021 02:10:11 +0530 Subject: [PATCH 41/55] Create dijkstra.js --- Dijkstra's Algorithm/dijkstra.js | 30 ++++++++++++++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 Dijkstra's Algorithm/dijkstra.js 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; +} From 6208756768c7957a02a7f6842ac1c71cb2ebe14e Mon Sep 17 00:00:00 2001 From: BugHunters-bug <91728280+BugHunters-bug@users.noreply.github.com> Date: Sun, 24 Oct 2021 17:59:28 +0530 Subject: [PATCH 42/55] renamed file --- Radix sort/{Radix_sort.cpp.txt => Radix_sort.cpp} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename Radix sort/{Radix_sort.cpp.txt => Radix_sort.cpp} (99%) diff --git a/Radix sort/Radix_sort.cpp.txt b/Radix sort/Radix_sort.cpp similarity index 99% rename from Radix sort/Radix_sort.cpp.txt rename to Radix sort/Radix_sort.cpp index 93ebc60..927cf97 100644 --- a/Radix sort/Radix_sort.cpp.txt +++ b/Radix sort/Radix_sort.cpp @@ -44,4 +44,4 @@ int main() { radixSort(arr, n, max); cout << "Data after Sorting: "; display(arr, n); -} \ No newline at end of file +} From 433eed065eb5134ee105787a3c54d2f044263f13 Mon Sep 17 00:00:00 2001 From: Bhoomika182 Date: Sun, 24 Oct 2021 18:23:37 +0530 Subject: [PATCH 43/55] added 0-1 knapsack.cpp --- 0-1 knapsack.cpp/0-1 knapsack.cpp.txt | 46 +++++++++++++++++++++++++++ 1 file changed, 46 insertions(+) create mode 100644 0-1 knapsack.cpp/0-1 knapsack.cpp.txt diff --git a/0-1 knapsack.cpp/0-1 knapsack.cpp.txt b/0-1 knapsack.cpp/0-1 knapsack.cpp.txt new file mode 100644 index 0000000..cd8b16e --- /dev/null +++ b/0-1 knapsack.cpp/0-1 knapsack.cpp.txt @@ -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 \ No newline at end of file From 5153f4840d1d3d17bac09815812575017233072b Mon Sep 17 00:00:00 2001 From: Mohit <58560983+mohit-003@users.noreply.github.com> Date: Sun, 24 Oct 2021 18:34:49 +0530 Subject: [PATCH 44/55] create linearsearch.js linear search in java script. --- Linear Search/linearsearch.js | 8 ++++++++ 1 file changed, 8 insertions(+) create mode 100644 Linear Search/linearsearch.js 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 +} From fa2194a415a34636ffbc1fa8e93b6010786a274b Mon Sep 17 00:00:00 2001 From: Mohit <58560983+mohit-003@users.noreply.github.com> Date: Sun, 24 Oct 2021 18:37:44 +0530 Subject: [PATCH 45/55] create binarysearch.js Binary search in java script --- BinarySearch/binarysearch.js | 37 ++++++++++++++++++++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 BinarySearch/binarysearch.js 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 @@ + From 561f0e756d73b6d8d1cabe9af939ec261f8462fb Mon Sep 17 00:00:00 2001 From: Mohit <58560983+mohit-003@users.noreply.github.com> Date: Sun, 24 Oct 2021 18:40:10 +0530 Subject: [PATCH 46/55] create fibonacci.js Fibonacci series in Java-Script --- Fibonacci series/fibonacci.js | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Fibonacci series/fibonacci.js diff --git a/Fibonacci series/fibonacci.js b/Fibonacci series/fibonacci.js new file mode 100644 index 0000000..00dbeac --- /dev/null +++ b/Fibonacci series/fibonacci.js @@ -0,0 +1,14 @@ + From 8300e298dd48a91a4dae1a636aed0de864287ca4 Mon Sep 17 00:00:00 2001 From: Mohit <58560983+mohit-003@users.noreply.github.com> Date: Sun, 24 Oct 2021 18:43:51 +0530 Subject: [PATCH 47/55] create armstron_number.js Armstrong number in java script --- Armstrong Number/armstrong_number.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Armstrong Number/armstrong_number.js 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.`); +} From c7988984a88e3e36c4387ff4355bd33d259ac36e Mon Sep 17 00:00:00 2001 From: BugHunters-bug <91728280+BugHunters-bug@users.noreply.github.com> Date: Sun, 24 Oct 2021 18:47:33 +0530 Subject: [PATCH 48/55] renamed file --- 0-1 knapsack.cpp/{0-1 knapsack.cpp.txt => 0-1 knapsack.cpp} | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) rename 0-1 knapsack.cpp/{0-1 knapsack.cpp.txt => 0-1 knapsack.cpp} (99%) diff --git a/0-1 knapsack.cpp/0-1 knapsack.cpp.txt b/0-1 knapsack.cpp/0-1 knapsack.cpp similarity index 99% rename from 0-1 knapsack.cpp/0-1 knapsack.cpp.txt rename to 0-1 knapsack.cpp/0-1 knapsack.cpp index cd8b16e..12459c2 100644 --- a/0-1 knapsack.cpp/0-1 knapsack.cpp.txt +++ b/0-1 knapsack.cpp/0-1 knapsack.cpp @@ -43,4 +43,4 @@ int main() return 0; } -// This \ No newline at end of file +// This From d870f995fe90f00bf564d79d9bed859bd28b470d Mon Sep 17 00:00:00 2001 From: PrabhaKumar Date: Sun, 24 Oct 2021 21:57:38 +0530 Subject: [PATCH 49/55] added hufman code --- hufman code/New Text Document.txt | 0 hufman code/hufman_code.c | 181 ++++++++++++++++++++++++++++++ 2 files changed, 181 insertions(+) create mode 100644 hufman code/New Text Document.txt create mode 100644 hufman code/hufman_code.c diff --git a/hufman code/New Text Document.txt b/hufman code/New Text Document.txt new file mode 100644 index 0000000..e69de29 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 From 41368fb99c780dff8f8f272a4016c7346ad74dd2 Mon Sep 17 00:00:00 2001 From: vaibhav mishra <89639461+VaibhavM01@users.noreply.github.com> Date: Mon, 25 Oct 2021 10:55:25 +0530 Subject: [PATCH 50/55] added jumpSearch.js Implemented Jumpsearch in javaScript --- Jump Search/jumpSearch.js | 26 ++++++++++++++++++++++++++ 1 file changed, 26 insertions(+) create mode 100644 Jump Search/jumpSearch.js 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; +} From b23f4378337d0a0d79f4e2ad258ad23b31bfdbcf Mon Sep 17 00:00:00 2001 From: BugHunters-bug <91728280+BugHunters-bug@users.noreply.github.com> Date: Thu, 28 Oct 2021 12:54:46 +0530 Subject: [PATCH 51/55] delete newtextdocument.txt --- hufman code/New Text Document.txt | 0 1 file changed, 0 insertions(+), 0 deletions(-) delete mode 100644 hufman code/New Text Document.txt diff --git a/hufman code/New Text Document.txt b/hufman code/New Text Document.txt deleted file mode 100644 index e69de29..0000000 From da3c67b8256bed4d5b90ab8c26a9ff1dd939113c Mon Sep 17 00:00:00 2001 From: Izuku29 <89025886+Izuku29@users.noreply.github.com> Date: Thu, 28 Oct 2021 22:57:40 +0530 Subject: [PATCH 52/55] fibonacci in c using a recursive function --- Fibonacci series/fibonacci in c | 14 ++++++++++++++ 1 file changed, 14 insertions(+) create mode 100644 Fibonacci series/fibonacci in c diff --git a/Fibonacci series/fibonacci in c b/Fibonacci series/fibonacci in c new file mode 100644 index 0000000..b59d44f --- /dev/null +++ b/Fibonacci series/fibonacci in 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; +} From e45968b56c0ed146584911baa3a595ed0aaa1a69 Mon Sep 17 00:00:00 2001 From: BugHunters-bug <91728280+BugHunters-bug@users.noreply.github.com> Date: Fri, 29 Oct 2021 12:51:30 +0530 Subject: [PATCH 53/55] rename --- Fibonacci series/{fibonacci in c => fibonacci.c} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename Fibonacci series/{fibonacci in c => fibonacci.c} (100%) diff --git a/Fibonacci series/fibonacci in c b/Fibonacci series/fibonacci.c similarity index 100% rename from Fibonacci series/fibonacci in c rename to Fibonacci series/fibonacci.c From fb2c501bf9ad0d4ee13a0d3ac78cfafccf5bb31b Mon Sep 17 00:00:00 2001 From: chakeson <80765479+chakeson@users.noreply.github.com> Date: Fri, 29 Oct 2021 14:24:11 +0200 Subject: [PATCH 54/55] Added Luhns algorithm --- Luhn algorithm/Luhn.py | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 Luhn algorithm/Luhn.py 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 From 130ae49ed6b093ff83a41989575b0537b2032c44 Mon Sep 17 00:00:00 2001 From: cheemra <93471584+cheemra@users.noreply.github.com> Date: Sun, 31 Oct 2021 21:52:37 +0530 Subject: [PATCH 55/55] Create tree_dsa.cpp --- Tree/tree_dsa.cpp | 129 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) create mode 100644 Tree/tree_dsa.cpp 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]; + } +}