Showing posts with label datastructures and algorithm. Show all posts
Showing posts with label datastructures and algorithm. Show all posts

Tuesday, October 8, 2013

Advanced Data Structures and Algorithm Analysis Assessment 1(October 2013)

Part A
Answer in brief
1)Show that f(n) = (n +1)3 is O(n3).
2)Write the algorithm for Insertion sort and derive the time complexity for worst case.

Part B
Answer in detail.

1)

For the Above BST list out Inorder,Preorder and postorder traversal.
give pseudo code for performing Insertion and deletion in BST
2)List out the various asymptotic notations used to represent the complexity of an algorithm.State the signeficance of every notation.Compare and contrast the same.

Friday, October 4, 2013

comparison of running time of merge sort and insertion sort

#include
#include
using namespace std;
#define MAXSIZE 200000
class sort{
int b[MAXSIZE + 1];
public:
void insertion_sort(int a[],int n)
{
for(int i=1;i{
   int j;
   int key = a[i];
  for(j=i-1;j>=0;j--)
  {
   if(a[j]<=key)
   break;
   a[j+1]=a[j];  
  }
  a[j+1]=key;
}
}
public:
void merge_sort(int a[],int n)
{
 mergesort(a,0,n-1);
}

void mergesort(int a[],int i,int j)
{
    int mid;
    if(i    {
        mid = (i+j)/2;
        mergesort(a,i,mid);
        mergesort(a,mid+1,j);
        merge(a,i,mid,j);
    }
}

void merge(int a[],int low,int mid,int high)
{
    int h,i,j,k;
    h=low;
    i=low;
    j=mid+1;
    while(h<=mid && j<= high)
    {
        if(a[h] <= a[j])
        b[i]=a[h++];
        else
        b[i]=a[j++];
        i++;
       
    }
    if(h>mid)
    {
        for(k=j;k<=high;k++)
        b[i++]=a[k];
     
    }
    else
    {
       for(k=h;k<=mid;k++)
        b[i++]=a[k];
     
    }
    for(k=low;k<=high;k++)
    {
        a[k]=b[k];
    }
}
};
int main()
{
int a[MAXSIZE];
int b[MAXSIZE];
int temp = MAXSIZE;
for(int i=0;i{
  //int temp = random()%10000 + 1;
  a[i]=temp;
  b[i]=temp;
  temp= temp-1;
}
sort s;
int t1,t2,t3;
t1=clock();
s.merge_sort(b,MAXSIZE);
t2=clock();
s.insertion_sort(a,MAXSIZE);
t3=clock();
int size = MAXSIZE;
cout<<"The time for mergesort for n ="<< size << " is"<< t2-t1<<"\n";
cout<<"The time for insertion sort for n = "<< size <<"is "<//cout<<"\n"<//for(int i=0;i//{
//cout<//}
//cout<//for(int i=0;i//{
//cout<//}
return 0;
}

Thursday, September 26, 2013

P,NP,NP-complete,NP-Hard

P
A problem is said to have P complexoty if it can be solved by a deterministic turung machine(computer).
eg
Find if a graph can be coloured with two colors wothout any vertices being monochromaric.

NP
A problem is said to be NP if it can be solved in polynomial run time by Non deterministic Turing machine and the solution can be verified in polynomial run time by a deterministic Turing machine.
A non deterministic Turing machine is hypothetical computer with infinite parallel processing capability.

eg.
Verify is numbers x,y have an integer factor such that 1
NP-Complete

A problem is NP complete if it is NP and It can be reduced to another NP complete problem in polynomial run time by a deterministic Turing machine.
since all NP complete programs can be reduced to each other is there exists solution in polynomial run time for one NP complete problem then all NP complete problems have solution with polynomial run-time.
If any NP complete problem is solved in polynomial run time then P=NP
eg.
Binary Satisfactory problem(verify if there exists an interpretation which satisfies the given Boolean expression.)


NP-Hard
A problem is said to be NP hard if there exists an NP complete problem that can be reduced to the given problem.These problems are at least as hard as the hardest NP problem.NP hard problem need not be NP i.e they need not be solvable in polynomial run-time by Non deterministic Turing machine.
eg.
Travalling salesman problem.

P=NP
If an NP complete problem is proved to have solution in polynomial run time then all NP problems will have solution in polynomial run time.
If P=NP then there will be huge consequences particularly in cryptography since most of the modern algorithms are based on the assumption that the problem to find prime factors of a number is not solvable in polynomial run time.

Wednesday, September 25, 2013

binary search tree

The following is a link list implementation of BST I found on net,
I have made some changes to it if you found any error inform me I will fix it.

#include
using namespace std;

class BinarySearchTree
{
    private:
        struct tree_node
        {
           tree_node* left;
           tree_node* right;
           int data;
        };
        tree_node* root;
    public:
        BinarySearchTree()
        {
           root = NULL;
        }
        bool isEmpty() const { return root==NULL; }
        void print_inorder();
        void inorder(tree_node*);
        void print_preorder();
        void preorder(tree_node*);
        void print_postorder();
        void postorder(tree_node*);
        void insert(int);
        void remove(int);
};

// Smaller elements go left
// larger elements go right
void BinarySearchTree::insert(int d)
{
    tree_node* temp = new tree_node;
    tree_node* parent;
    temp->data = d;
    temp->left = NULL;
    temp->right = NULL;
    parent = NULL;
  // is this a new tree?
  if(isEmpty()) root = temp;
  else
  {
    //Note: ALL insertions are as leaf nodes
    tree_node* current;
    current = root;
    // Find the Node's parent
    while(current)
    {
        parent = current;
        if(temp->data > current->data) current = current->right;
        else current = current->left;
    }

    if(temp->data < parent->data)
       parent->left = temp;
    else
       parent->right = temp;
  }
}

void BinarySearchTree::remove(int d)
{
    //Locate the element
    bool found = false;
    if(isEmpty())
    {
        cout<<" This Tree is empty! "<        return;
    }
    tree_node* current;
    tree_node* parent;
    current = root;
    while(current != NULL)
    {
         if(current->data == d)
         {
            found = true;
            break;
         }
         else
         {
             parent = current;
             if(d>current->data) current = current->right;
             else current = current->left;
         }
    }
    if(!found)
    {
        cout<<" Data not found! "<<"\n";
        return;
    }


// 3 cases :
    // 1. We're removing a leaf node
    // 2. We're removing a node with a single child
    // 3. we're removing a node with 2 children

    // Node with single child
    if((current->left == NULL && current->right != NULL) || (current->left != NULL && current->right == NULL))
    {
       if(current->left == NULL && current->right != NULL)// right child present, no left child
       {
           if(parent->left == current)
           {
             parent->left = current->right;
             delete current;
           }
           else
           {
             parent->right = current->right;
             delete current;
           }
       }
       else  // left child present, no right child
       {
          if(parent->left == current)
           {
             parent->left = current->left;
             delete current;
           }
           else
           {
             parent->right = current->left;
             delete current;
           }
       }
     return;
    }

if( current->left == NULL && current->right == NULL) //We're looking at a leaf node
    {
        if(parent->left == current) parent->left = NULL;
        else parent->right = NULL;
delete current;
return;
    }


    //Node with 2 children
    // replace node with smallest value in right subtree
    if (current->left != NULL && current->right != NULL)
    {
        tree_node* chkright;
        chkright = current->right;
        if((chkright->left == NULL) && (chkright->right == NULL))
        {
            current->data = chkright->data;
            delete chkright;
            current->right = NULL;
        }
        else // right child has children
        {
            //if the node's right child has a left child
            // Move all the way down left to locate smallest element

            if((current->right)->left != NULL)
            {
                tree_node* leftcurr;
                tree_node* leftcurrp;
                leftcurrp = current->right;
                leftcurr = (current->right)->left;
                while(leftcurr->left != NULL)
                {
                   leftcurrp = leftcurr;
                   leftcurr = leftcurr->left;
                }
current->data = leftcurr->data;
                delete leftcurr;
                leftcurrp->left = NULL;
           }
           else
           {
               tree_node* temp;
               temp = current;
               current = current->right;
               delete temp;
           }

        }
return;
    }

}

void BinarySearchTree::print_inorder()
{
  inorder(root);
}

void BinarySearchTree::inorder(tree_node* p)
{
    if(p != NULL)
    {
        if(p->left) inorder(p->left);
        cout<<" "<data<<" ";
        if(p->right) inorder(p->right);
    }
    else return;
}

void BinarySearchTree::print_preorder()
{
  preorder(root);
}

void BinarySearchTree::preorder(tree_node* p)
{
    if(p != NULL)
    {
        cout<<" "<data<<" ";
        if(p->left) preorder(p->left);
        if(p->right) preorder(p->right);
    }
    else return;
}

void BinarySearchTree::print_postorder()
{
  postorder(root);
}

void BinarySearchTree::postorder(tree_node* p)
{
    if(p != NULL)
    {
        if(p->left) postorder(p->left);
        if(p->right) postorder(p->right);
        cout<<" "<data<<" ";
    }
    else return;
}

int main()
{
    BinarySearchTree b;
    int ch,tmp,tmp1;
    do
    {
       cout<       cout<<" Binary Search Tree Operations "<<"\n";
       cout<<" ----------------------------- "<<"\n";
       cout<<" 1. Insertion/Creation "<<"\n";
       cout<<" 2. In-Order Traversal "<<"\n";
       cout<<" 3. Pre-Order Traversal "<<"\n";
       cout<<" 4. Post-Order Traversal "<<"\n";
       cout<<" 5. Removal "<<"\n";
       cout<<" 6. Exit "<<"\n";
       cout<<" Enter your choice : ";
       cin>>ch;
       switch(ch)
       {
           case 1 : cout<<" Enter Number to be inserted : ";
                    cin>>tmp;
                    b.insert(tmp);
                    break;
           case 2 : cout<                    cout<<" In-Order Traversal "<<"\n";
                    cout<<" -------------------"<<"\n";
                    b.print_inorder();
                    break;
           case 3 : cout<                    cout<<" Pre-Order Traversal "<<"\n";
                    cout<<" -------------------"<<"\n";
                    b.print_preorder();
                    break;
           case 4 : cout<                    cout<<" Post-Order Traversal "<<"\n";
                    cout<<" --------------------"<<"\n";
                    b.print_postorder();
                    break;
           case 5 : cout<<" Enter data to be deleted : ";
                    cin>>tmp1;
                    b.remove(tmp1);
                    break;
           case 6 : cout<<"Exiting";
                    return 0;
                    break;
            default : cout<<"Enter valid choice";
                        break;
       }
   
    }while(ch!=6);
}


Mergesort

The following is the algorithm of mergesort

1)split the array into two almost equal halves(subarray 1 ,subarray 2)
2)sort the subarray 1
3)sort the subarray 2
4)merge the sorted sub arrays
5)follow steps 1 to 4 recursively for sorting the sub arrays till array size is 1.

algorithm for merging
1)set counters i and j to the beginning of sub arrays 1 and 2
2)compare the elements referred by i and j and copy the smaller element to a temporary array and increment the respective counter.
3)repeat step 2 till elements of subarray 1 or subarray 2 are exhausted.
4)copy the remaining elements of the array that is not exhausted to the temporary array in the same order.
5)copy the content of temporary array back to original array.


The following program implements mergesort

#include
using namespace std;

void mergesort(int *,int,int);
void merge(int*,int,int,int);
int b[100];

int main()
{
   int a[100],i,n;
   cout << "Enter the number of terms";
   cin>>n;
   cout<<"Enter elements";
   for(i=0;i   {
       cout<<"Enter the element in position "<       cin>>a[i];
    }
    mergesort(a,0,n-1);
    cout<<"After mergesort";
    for(i=0;i   {
       cout<    }
   return 0;
}

void mergesort(int a[],int i,int j)
{
    int mid;
    if(i    {
        mid = (i+j)/2;
        mergesort(a,i,mid);
        mergesort(a,mid+1,j);
        merge(a,i,mid,j);
    }
}

void merge(int a[],int low,int mid,int high)
{
    int h,i,j,k;
    h=low;
    i=low;
    j=mid+1;
    while(h<=mid && j<= high)
    {
        if(a[h] <= a[j])
        b[i]=a[h++];
        else
        b[i]=a[j++];
        i++;
     }
    if(h>mid)
    {
        for(k=j;k<=high;k++)
        b[i++]=a[k];
';
    }
    else
    {
       for(k=h;k<=mid;k++)
        b[i++]=a[k];
     
    }
    for(k=low;k<=high;k++)
    {
        a[k]=b[k];
    }
}