Showing posts with label Algorithms. Show all posts
Showing posts with label Algorithms. Show all posts

Thursday, 6 August 2015

Backtracking Algorithms : Explaining Cindy's Puzzle with a C++ Program




Classic text books in Algorithm Analysis like Cormen, Leiserson and Rivest, Sedgewick and Flajolet, etc. often neglect or give least preference to the algorithm development technique called backtracking. Even those textbooks discussing backtracking only discuss few selected problems. A classic problem discussed along with backtracking is the eight queens puzzle. Often this problem is unappreciated by persons not well versed in the game of Chess. Here I am trying to explain backtracking using a very simple game often called ‘Cindy’s puzzle’.

The game Cindy’s puzzle involves n Red marbles, n Green marbles and a playing board which consists simply of a line of 2n+1 spaces to put the marbles in. Start with the Red marbles all at one end (say, the left), the Green marbles all at the other end, and a free space in between. For n=2, the initial arrangement on the board is shown below.



To denote this position we use the notation |R|R| _ |G|G| is used.
The aim of the puzzle is to reverse the positions of the marbles as shown below.


So the solution for the puzzle can be denoted as |G|G| _ |R|R|.
The movements of the marbles are restricted by the following rules.
The Red marbles can only move to the right, and the Green marbles can only move to the left (no backing up). At each move, a marble can either
  • Move one space ahead, if that space is clear, or
  • Jump ahead over exactly one marble of the opposite color, if the space just beyond that marble is clear.
I am trying to develop a backtracking algorithm to solve this puzzle. The algorithm will be able to produce one particular solution to this puzzle. For example for n=2, the solution steps are given below.

           |R|R| _ |G|G|

        |R|R|G| _ |G|

        |R| _ |G|R|G|

        | _ |R|G|R|G|

        |G|R| _ |R|G|

        |G|R|G|R| _ |

        |G|R|G| _ |R|

        |G| _ |G|R|R|

        |G|G| _ |R|R|

Of course this is an ideal solution where no backtracking is used but in the proposed backtracking algorithm, if non winnable situation arises backtracking is applied to go back to a previous state and continue the search for a solution. 

Monday, 25 February 2013

Tower of Hanoi: Non Recursive Solutions

  The Recursive solution for the Tower of Hanoi problem has been discussed in another post. Here I am discussing two non recursive algorithms to solve the problem.
  • Iterative Solution

  Alternate moves between the smallest disk and a non-smallest disk is carried out in the iterative solution. When moving the smallest disk, always move it to the next position in the same direction. If there is no peg position in the chosen direction, move the disk to the opposite end, but then continue to move in the correct direction. Doing this will complete the puzzle using the fewest number of moves to do so.

Figure Below Shows the Output for 3 Disks


  • Binary Solution
Disk positions may be determined more directly from the binary representation of the move number. The following rules are used to find the moves.
  1. There is one binary digit for each disk.
  2. The most significant bit represents the largest disk. A value of 0 indicates that the largest disk is on the initial peg, while a 1 indicates that it's on the final peg.
  3. The bit string is read from left to right, and each bit can be used to determine the location of the corresponding disk.
  4. A bit with the same value as the previous one means that the corresponding disk is stacked on top the previous disk on the same peg.
  5. A bit with a different value to the previous one means that the corresponding disk is one position to the left or right of the previous one. The initial peg is on the left and the final peg is on the right. The right peg counts as one peg "left" of the left peg, and vice versa. Let n be the number of greater disks that are located on the same peg as their first greater disk and add 1 if the largest disk is on the left peg. If n is even, the disk is located one peg to the left, if n is odd, the disk located one peg to the right.
Figure Below Shows the Output for 3 Disks


Thursday, 14 February 2013

Shell Sort

  Shell Sort is a sorting algorithm which works in sub quadratic time. Shell Sort works by comparing elements that are distant rather than adjacent elements in an array or list. Shell Sort makes multiple passes through a list and sorts the lists using insertion sort. Shell Sort improves the insertion sort by quickly shifting values to their destinations. Shell Sort is also called diminishing increment sort because the distance between comparisons decreases as the algorithm proceeds. In the final phase adjacent elements are compared. The efficiency of Shell Sort largely depends on the increment sequence. It is faster than bubble sort, insertion sort and selection sort. But Shell Sort is slower than heap sort, merge sort and quick sort.

Wednesday, 30 January 2013

Dijkstra's Algorithm: C/C++ Program

Dijkstra's algorithm is used to solve the Single Source Shortest Path problem in Graphs. The Algorithm's time complexity is O(n2) for a graph with n nodes. Dijkstra's algorithm works only for a graph with non-negative edge path costs. 


Wednesday, 23 January 2013

KMP Algorithm: C/C++ Program

Knuth–Morris–Pratt algorithm

  The Knuth-Morris-Pratt Algorithm (KMP Algorithm) is a string searching algorithm. The performance of KMP Algorithm is far better than the naive string searching algorithm. The time complexity of KMP algorithm is O(m+n). Here m is the length of the text and n is the length of the pattern (sub string) to be searched. KMP algorithm also requires a preprocessing time of the order of O(n).

Click here to download the C Program implemeting KMP Algorithm.
Click here to download the C++ Program implemeting KMP Algorithm.

The Naive String Searching Algorithm.

  The Naive string searching algorithm is also called the simple string searching algorithm. It employs a brute force technique to identify the presence of a pattern in the given text. Even though the working of the algorithm can be understood easily, it is not an efficient algorithm. The time complexity of the algorithm to check for a sub string is O(mn) where m is the length of the text and n is the length of the pattern (sub string) to be searched. But no preprocessing is required for this algorithm.

Click here to download the C Program implementing The Naive String Searching Algorithm. 
Click here to download the C++ Program implementing The Naive String Searching Algorithm.

Monday, 21 January 2013

Floyd-Warshall Algorithm: C/C++ Program

  Floyd-Warshall algorithm (Also called Floyd's Algorithm) is used to solve the All-Pairs Shortest Path problem in Graphs. The Algorithm's time complexity is O(n3) for a graph with n nodes. The algorithm is given below.

for each vertex v
     dist[v][v] ← 0
for each edge (u,v)
     dist[u][v] ← w(u,v) 
for k from 1 to |V|       
     for i from 1 to |V|
         for j from 1 to |V|
                if dist[i][k] + dist[k][j] < dist[i][j] then   
                     dist[i][j] ← dist[i][k] + dist[k][j]  
  Floyd-Warshall algorithm is essentially same as Warshall's algorithm used to find the transitive closure of a relation R. Floyd-Warshall algorithm is an example for Dynamic Programming.

Click here to download the C Program implementing Floyd-Warshall Algorithm.   
Click here to download the C++ Program implementing Floyd-Warshall Algorithm. 

C/C++ Program to find the Transitive Closure of a Relation

Warshall's Algorithm
  To find the Transitive Closure of a Relation an algorithm called Warshall's Algorithm is used. The transitive closure of a Binary Relation R on a Set X is the transitive relation R+ on the set X such that R+ contains R and R+ is minimal. The transitive closure can answer reachability question in case of graphs. Warshall's algorithm is also the back bone of Floyd-Warshall algorithm used to solve the All-Pairs Shortest Path problem in graphs. The Time Complexity of Warshall's Algorithm is O(n3) for a Relation involving n elements.

Tuesday, 4 December 2012

Binary Search


  Binary Search is used to find a key number from a list of numbers. The time complexity of the algorithm is O(nlog n). The advantage is the shorter time requirement and the disadvantage is that Linear Search works only with a sorted list of numbers. So Linear Search is a not a general search algorithm which can be applied on any list.

Advantages:
  •  The Algorithm takes only O(n log n) time for finding the item.
Disadvantages:
  • Gives the correct output only if the array of numbers is sorted.

Click here to download the C Program to perform Binary Search.
Click here to download the C++ Program to perform Binary Search.

Linear Search



  Linear Search is used to find a key number from a list of numbers. The time complexity of the algorithm is O(n). There are other algorithms which solves the problem within shorter period of time. But the advantage is that Linear Search even works with an unsorted list of numbers. So Linear Search is a very general search which can be applied on any list.

Advantages:
  •  The Algorithm will work for unsorted array of numbers.
  •  Simple.
Disadvantages:
  • Linear time Complexity ( O(n) ).  

Click here to download the C Program to perform Linear Search.
Click here to download the C++ Program to perform Linear Search.

Monday, 3 December 2012

Finding the Median in Linear Time


  This article is about a Median finding Algorithm. Here we try to find the median element of a List. Let us assume the list is sorted in ascending order then the Median is the ((N+1)/2)th element if N is odd and elements (N/2) and ((N/2)+1) if N is even. The first method that comes to our mind is to sort the list and then find the Median element afterwards. We can sort using a quadratic time sorting algorithm like Bubble Sort or Insertion Sort, or better yet we can go for one of the n log n sorts like Heap Sort or Quick Sort. Is this the lower limit for this problem ? The answer is a No. We can have a linear time algorithm to find the Median element of a list. A modified version of Quick Sort called Quick Median is used here. This algorithm takes O(n) time to find the Median element in the average case. The only problem with this algorithm is that the worst case time requirement is O(n2). To over come this problem we have to use an algorithm called Median of Medians to find an approximate Median value which is used as a pivot to divide the list into two. The algorithm Median of Medians will be discussed in a different post.

Advantages:
  • Average case running time of O(n).
Disadvantages:
  • Worst case running time is O(n2).

To simplify the problem it is assumed that the list contains only odd number of elements and the median is the  ((N+1)/2)th element in the sorted list.

Click here to download the C Program to find the Median in linear time.
Click here to download the C++ Program to find the Median in linear time.

A Linear Selection Algorithm


  Here in this article I am writing about a Selection Algorithm. Here we try to find out the Nth element of a List. Let us assume the list is sorted in ascending order then 1st element is the smallest element of the list, the Nth element is the largest in the list and the Median is the ((N+1)/2)th element if N is odd and elements (N/2) and ((N/2)+1) if N is even. 

  The first method that comes to our mind is to sort the list and then find the Nth element afterwards. We can sort using a quadratic time sorting algorithm like Bubble Sort or Insertion Sort, or better yet we can go for one of the n log n sorts like Heap Sort or Quick Sort. Is this the lower limit for this problem ? The answer is a No. We can have a linear time algorithm to find the Nth element. A modified version of Quick Sort called Quick Select is used here. This algorithm takes O(n) time to find the Nth element in the average case. The only problem with this algorithm is that the worst case time requirement is O(n2). To over come this problem we have to use an algorithm called Median of Medians. The algorithm Median of Medians will be discussed in a different post.

Advantages:
  • Average case running time is O(n).
Disadvantages:
  • Worst case running time is O(n2).

Click here to download the C Program to perform Selection in linear time.
Click here to download the C++ Program to perform Selection in linear time.


Tower of Hanoi Problem


  The Tower of Hanoi Problem is a mathematical problem. There are three rods and on one of the rods there are some disks of unique size. The problem is to move the disks from one rod to the second one, using the third rod as an intermediary. But while moving the disks the following rules should not be violated.
  • Only one disk can be moved at a time.
  • A larger disk should not be placed on top of a smaller disk.
  • Only the disk on the top of a rod can be moved. 
The number of moves required to solve the Tower of Hanoi Problem with N Disks is 2N-1. 
  Unlike many other problems discussed here, the time complexity of the Tower of Hanoi problem is not polynomial. It takes an exponential time O(2n) to solve the problem. The figures given below illustrates the solution for the Tower of Hanoi problem with three disks. It takes 7 moves to solve the problem.

Initial Position
After Move 1
After Move 2
After Move 3
After Move 4
After Move 5
After Move 6
After Move 7




Click here to download the C Program to solve the Tower of Hanoi problem.
Click here to download the C++ Program to solve the Tower of Hanoi problem.

Sunday, 2 December 2012

Program for Constructing a Max Heap



  Heap is a data structure that obeys the heap property. Heap property sets some restrictions on the relationship between the parent node and child nodes. In a Min Heap the key value of every parent node must be less than or equal to the key value of its child nodes. In a Max Heap the key value of every parent node must be greater than or equal to the key value of its child nodes. The program is to create a max heap from a list of numbers. 

Identifying the Left and Right Child nodes






The Tree Representation of the Max Heap



Click here to download the C Program to construct a Max Heap.
Click here to download the C++ Program to construct a Max Heap.



Heap Sort

  Heap Sort is the third of the famous n log n sorts. Heap Sort is an in-place comparison sort. In the example program given below a Max-Heap is used to sort the list of numbers. on average the Heap Sort is slightly poorer when compared with Quick Sort. But the worst case time of Heap Sort is still O(n log n).

Click here to download the C Program to perform Heap Sort.
Click here to download the C++ Program to perform Heap Sort.

Saturday, 1 December 2012

Quick Sort



  Quick Sort is an n log n sort. On average it takes O(n log n) time to sort the given list. Quick Sort is usually implemented as an in-place sorting algorithm. The disadvantage with Quick Sort is that in the worst case Quick Sort only gives a quadratic time perfromance ( O(n2) ). This happens when the list to be sorted is already sorted. But on average Quick Sort slightly outperforms both Merge Sort and Heap Sort.

Click here to download the C Program to perform Quick Sort.
Click here to download the C++ Program to perform Quick Sort.

Merge Sort


  Merge Sort is of the order of n log n, which means the average running time is O (n log n). It is a comparison sort. The worst case memory requirement of Merge Sort is n. That is Merge Sort will take 80 bytes of storage to sort 10 numbers assuming 4 bytes are used to store a number. So it requires twice the memory to perform sorting when compared with another n log n sort called Quick Sort.

Click here to download the C Program to perform Merge Sort.
Click here to download the C++ Program to perform Merge Sort.

Sorting Algorithms - A Comparison




  Here I am comparing three Sorting Algorithms which takes quadratic time to perform the operation. The three sorting techniques under consideration are Bubble Sort, Selection Sort and Insertion Sort.

                                      Bubble Sort

  Bubble Sort is a comparison sort, which means the sorting is done by comparing elements in the list to be sorted. Bubble Sort is an in-place sorting technique, which means it only requires constant additional space to perform the sorting. The additional space requirement is to hold the temporary values while swapping two numbers. Bubble Sort takes O(n2) time to perform the sorting. The two advantages with Bubble Sort are the best case performance of linear time ( O(n) ) if the list is already sorted and the inherent simplicity of the algorithm. Most often this is the algorithm which comes to the mind of a person when asked to perform sorting.

Click here to download the C Program to perform Bubble Sort.
Click here to download the C++ Program to perform Bubble Sort.


                                      Selection Sort

  This is another sorting algorithm which takes quadratic time to perform the operation. Selection sort is also an in-place comparison sort. One advantage with Selection Sort is its simplicity. Unlike Bubble Sort, Selection Sort constructs the sorted list one by one after each iteration of the outer loop. So in situations where you can start working with the list even when it is not complete we must go for Selection Sort.

Click here to download the C Program to perform Selection Sort. 
Click here to download the C++ Program to perform Selection Sort. 

                                      Insertion Sort

  Insertion Sort also takes quadratic time to sort. It is also an in-place comparison sort. Insertion Sort gives slightly better performance when compared with the other two quadratic time sorts. The best case performance of Insertion Sort is linear just like Bubble Sort. But Insertion Sort also performs well if the list is partially sorted. So if you have to choose between the quadratic sorts, it is slightly better to choose Insertion Sort.

Click here to download the C Program to perform Insertion Sort. 
Click here to download the C++ Program to perform Insertion Sort.