Sunday, December 21, 2014

Spiral (ZigZag printing) Printing the Binary Tree nodes in C

This is a variant of level order printing. In level order printing we can use iterative or a queue based approach. Iterative option is still available in this one too.But we are trying to follow a non iterative approach here. Instead of a queue we will have two stacks for implementing Sprial printing (also called ZigZag printing) of the Binary Tree. First we push the root node to stack one. Then we visit both stacks and take the top item and store it in a temp variable, then we will pop the stack from which we had pushed the binary tree node. At the same time we will push into the alternate stack the children of the temporary node we had stored. On one stack we will push in right then left child order and in the other one we will be pushing in left and then right children order.

For a binary tree like below

                                         1
                                         / \
                                        2 3
                                       /\  /\
                                     4 5 6 7

 the spiral printing order will be as below:

 1
23
7654

 Below is the implementation:

Tuesday, December 16, 2014

Kadanes Algorithm for finding sub-array with maximum sum

Here is the Kadanes algorithm implementation in Python. Here we pass thru the array in a linear fashion. While we pass thru the array we keep adding the elements. As we add the elements we keep track of previous largest sum ever found. We compare the present sum with so far largest sum till we finish the entire array.

Sunday, December 7, 2014

Algorithm for inserting elements from the back of the Linked List to the elements on front of the array interleaving one node each.

Algorithm for printing reversing a array from mid element and inserting nodes between two nodes . 
For example

 -> 11 -> 10 -> 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> null 

should be converted to 

->11 -> 1 -> 10 -> 2 -> 9 -> 3 -> 8 -> 4 -> 7 -> 5 -> 6->null

Saturday, December 6, 2014

Algorithm to print combinations of elements in given order (Written in Java)

This is an algorithm to print combinations of elements in an array following the lexicographic order. For example if the given array is

{ 'a', 'b', 'c', 'd'}

then the answer should be

 ab, ac, ad, bc, bd, abc, abd, acd, bcd, abcd.


 Given below is the implementation:

Friday, December 5, 2014

Byte aligned malloc implementation

Usually when we call malloc we are returned with a address where the memory is allocated. But suppose if we want to ensure that the memory allocated is aligned with some value how can we implement such an malloc. Below is an implementation of that: