Posts

Knuth-Morris-Pratt Algorithm

Image
 Knuth-Morris-Pratt Algorithm              Knuth Morris Pratt (KMP) is an algorithm, which checks the characters from left to right. When a pattern has a sub-pattern appears more than one in the sub-pattern, it uses that property to improve the time complexity, also for in the worst case.            The KMP matching algorithm uses degenerating property (pattern having same sub-patterns appearing more than once in the pattern) of the pattern and improves the worst case complexity to O(n). The basic idea behind KMP’s algorithm is: whenever we detect a mismatch (after some matches), we already know some of the characters in the text of the next window. We take advantage of this information to avoid matching the characters that we know will anyway match.  Algorithm: findPrefix(pattern, m, prefArray) Begin    length := 0    prefArray[0] := 0    for all character index ‘i’ of pat...

Backtracking

BACKTRACKING                    Backtracking is an algorithmic-technique for solving problems recursively by trying to build a solution incrementally, one piece at a time, removing those solutions that fail to satisfy the constraints of the problem at any point of time (by time, here, is referred to the time elapsed till reaching any level of the search tree). Backtracking can be defined as a general algorithmic technique that considers searching every possible combination in order to solve a computational problem.  There are three types of problems in backtracking – Decision Problem – In this, we search for a feasible solution. Optimization Problem – In this, we search for the best solution. Enumeration Problem – In this, we find all feasible solutions.   PSEUDO CODE: 1. Recursive backtracking solution. void findSolutions(n, other params) : if (found a solution) : sol...

RECURSIVE INSERTION SORT

Image
 INSERTION SORT:                  Insertion sort is a simple sorting algorithm that works similar to the way you sort playing cards in your hands. The array is virtually split into a sorted and an unsorted part. Values from the unsorted part are picked and placed at the correct position in the sorted part.   EXAMPLE:   RECURSION IDEA: Base Case: If array size is 1 or smaller, return. Recursively sort first n-1 elements. Insert last element at its correct position in sorted array.   ALGORITHM: We are going to mimic the Iterative Insertion sort in the recursive implementation. We will create a function which will take the array and current index as input. In this function we will iterate through all the elements less than the current index and swap the elements based on the sorting order. If the index is less than 1 then will terminate the recu...