data structures for beginners

vinod’s work on data structures

SPARSE MATRIX ADDITION

Posted by Vinod on December 21, 2006

/******************************************************

-> This C++ program is to perform sparse matrix
   addition.

   THE FOLLOWING ASSUMPTIONS ARE MADE IN ORDER TO
 SIMPLIFY THE PROGRAM
 _______________________________________________

   1) The row numbers and column numbers are supposed
      to be start from 1.
 2) There are no duplicates in the input

-> Data structures used
 Matrix : multi linked list

-> This program works in microsoft vc++ in windows xp

*******************************************************/

#include<iostream.h>
#include<stdlib.h>

class sparse
{
private:
 int r;          // row number
 int c;          // column number
 sparse *rptr;   // row pointer
 sparse *cptr;   // column header
 int data;       // actual data
public:
 sparse * create(sparse*);
 void display(sparse*);
 void add(sparse*,sparse*);
};

sparse * sparse::create(sparse*h)
{
 cout<<“\nEnter the no. of rows ::”;
 cin>>r;
 cout<<“Enter the no. of columns ::”;
 cin>>c;

 // create the head node
 h=new sparse;
 h->r=r;
 h->c=c;
 h->rptr=h;
 h->cptr=h;
 h->data=0;

 // create column headers
 sparse *ptr;
 int i,j,d;
 ptr=h;
 for(i=1;i<=c;i++)
 {
  sparse *node;
  node=new sparse;
  node->r=0;
  node->c=i;
  node->data=0;
  node->rptr=h;
  node->cptr=node;

  ptr->rptr=node;
  ptr=node;
 }

 // create row headers
 ptr=h;
 for(i=1;i<=r;i++)
 {
  sparse *node;
  node=new sparse;
  node->r=i;
  node->c=0;
  node->data=0;
  node->rptr=node;
  node->cptr=h;

  ptr->cptr=node;
  ptr=node;
 }
 cout<<“\n now enter the non zero elements ”
  <<“one by one\n”;
 cout<<“\nEnter row number,column number,data\n”;
 cout<<“Enter (0 0 0) to stop ::”;
 cin>>i>>j>>d;
 if(i>r || j>c ||i<1 ||j<1)
 {
  cout<<” error input”;
  exit(1);
 }
 while(i&&j&&d)
 {
  sparse * row_header=h->cptr;
  sparse * column_header=h->rptr;

  // find the correct row header and column header
  while(row_header->r<i)
   row_header=row_header->cptr;

  while(column_header->c<j)
   column_header=column_header->rptr;

  sparse *ptr1;
  sparse *ptr2;

  // find the correct position to insert
  sparse*row_ptr=row_header;
  while(row_ptr->c<j)
  {
   ptr1=row_ptr;
   row_ptr=row_ptr->rptr;
   if(row_ptr==row_header)
    break;
  }

  sparse*column_ptr=column_header;
  while(column_ptr->r<i)
  {
   ptr2=column_ptr;
   column_ptr=column_ptr->cptr;
   if(column_ptr==column_header)
    break;
  }

  sparse *node;
  node=new sparse;
  node->r=i;
  node->c=j;
  node->data=d;

  ptr1->rptr=node;
  ptr2->cptr=node;
  node->rptr=row_ptr;
  node->cptr=column_ptr;

  cout<<“\nEnter row number,column number,data\n”;
  cout<<“Enter (0 0 0) to stop ::”;
  cin>>i>>j>>d;
  if(i>r || j>c )
  {
   cout<<” error input”;
   exit(1);
  }
 }
 return h;
}

void sparse::display(sparse*h)
{
 sparse *right;
 right=h->cptr;
 
 while(right!=h)
 {
  sparse *r=right;
  right=right->rptr;
  while(right!=r)
  {
   cout<<right->r
    <<‘\t'<<right->c
    <<‘\t'<<right->data<<endl;
   right=right->rptr;
  }
  right=right->cptr;
 }
}

void sparse::add(sparse*h1,sparse*h2)
{
 if(h1->r==h2->r && h1->c==h2->c)
  cout<<“The addition of the two given ”
   <<“sparse matrices is ::\n”;
 else
 {
  cout<<“addition is not possible”;
  exit(1);
 }
 sparse *r1;
 r1=h1->cptr;
 sparse *r2;
 r2=h2->cptr;
 
 while(r1!=h1)
 {
  sparse * p1=r1;
  r1=r1->rptr;

  sparse * p2=r2;
  r2=r2->rptr;

  while(r1!= p1 && r2!=p2)
  {
   if(r1->c==r2->c)
   {
    cout<<r1->r<<‘\t'<<r1->c<<‘\t’
    <<(r1->data+r2->data)<<endl;
    r1=r1->rptr;
    r2=r2->rptr;
   }
   else if(r1->c>r2->c)
   {
    cout<<r2->r<<‘\t'<<r2->c<<‘\t’
    <<r2->data<<endl;
    r2=r2->rptr;
   }
   else
   {
    cout<<r1->r<<‘\t'<<r1->c<<‘\t’
    <<r1->data<<endl;
    r1=r1->rptr;
   }
  }
  while(r1!=p1)
  {
   cout<<r1->r<<‘\t'<<r1->c<<‘\t’
    <<r1->data<<endl;
   r1=r1->rptr;
  }
  while(r2!=p2)
  {
   cout<<r2->r<<‘\t'<<r2->c<<‘\t’
    <<r2->data<<endl;
   r2=r2->rptr;
  }
  r1=r1->cptr;
  r2=r2->cptr;
 }
}

void main()
{
 cout<<“******************************************”;
 cout<<“\nThis program is to perform addition of \n”;
 cout<<” two sparse matrices \n”;
 cout<<“*******************************************\n”;
 sparse s;
 sparse *h1=NULL,*h2=NULL;
 cout<<“Enter the values for sparse matrix 1 ::\n”;
 cout<<“****************************************\n”;
 h1=s.create(h1);
 s.display(h1);
 cout<<“Enter the values for sparse matrix 2 ::\n”;
 cout<<“****************************************\n”;
 h2=s.create(h2);
 s.display(h2);
 s.add(h1,h2);
}

/*SAMPLE OUTPUT */

Posted in linear data structures | 5 Comments »

BELLMAN FORD’S SINGLE SOURCE SHORTEST PATH ALGORITHM

Posted by Vinod on December 21, 2006

/*************************************************************************

  -> This C++ program is to implement Bellmen Ford algorithm.

  -> Bellmen Ford algorithm solves the single source shortest paths
     problem in the general case in which edge weights may be negative.

  -> This algorithm returns true if the graph contains no
     negative-weight cycles that are reachable from the source
  else returns the shortest paths from the source.

  -> This program works in Microsoft VC++ environment in windows xp

  -> Data structures used:
        Graph :: Adjacency matrix

  -> Header files used :
        1)iostream.h
 2)stdlib.h

/*************************************************************************/

#include<iostream.h>
#include<stdlib.h>

#define MAX 20
#define INFINITY 9999

class bell_ford
{
private:
 int n;
 int graph[MAX][MAX];
 int start;
 int distance[MAX];
 int predecessor[MAX];
public:
 void read_graph();
 void initialize();
 void update();
 void check();
 void algorithm();
};

void bell_ford::read_graph()
{
 cout<<“Enter the no. of nodes in the graph ::”;
 cin>>n;
 cout<<“Enter the adjacency matrix for the graph ::\n”;
 for(int i=1;i<=n;i++)
  for(int j=1;j<=n;j++)
   cin>>graph[i][j];
 cout<<“Enter the start vertex ::”;
 cin>>start;
}

void bell_ford::initialize()
{
 for(int i=1;i<=n;i++)
 {
   distance[i]=INFINITY;
   predecessor[i]=0;
 }
 distance[start]=0;
}

void bell_ford::update()
{
 for(int i=1;i<=n-1;i++)
 {
  for(int u=1;u<=n;u++)
  {
   for(int v=1;v<=n;v++)
   {
    if(graph[u][v]!=0)
    {
     if(distance[v]>distance[u]+graph[u][v])
     {
      distance[v]=distance[u]+graph[u][v];
      predecessor[v]=u;
     }
    }
   }
  }
 }
}

void bell_ford::check()
{
 for(int u=1;u<=n;u++)
 {
  for(int v=1;v<=n;v++)
  {
   if(graph[u][v]!=0)
   {
    if(distance[v]>distance[u]+graph[u][v])
    {
     cout<<“does not exist’s “;
     return;
    }
   }
  }
 }

 cout<<“\n\nThere is no negative weight cycle and\n”;
 cout<<“****** The final paths and the distacnes are ******\n\n”;
 for(int i=1;i<=n;i++)
 {
  cout<<“path for node “<<i<<” is ::\n”;
  int arr[MAX],k=1;
  int j=i;
  while(predecessor[j]!=0)
  {
   arr[k]=predecessor[j];
   k++;
   j=predecessor[j];
  }
  for(–k;k>0;k–)
   cout<<arr[k]<<“->”;
  cout<<i<<endl;
  cout<<“distance is “<<distance[i]<<endl<<endl<<endl;
 }
}

void bell_ford::algorithm()
{
 read_graph();
 initialize();
 update();
 check();
}

void main()
{
 bell_ford obj;
 obj.algorithm();
}

Posted in graphs, shortest path algorithm | 1 Comment »

TOWERS OF HANOI

Posted by Vinod on December 21, 2006

/**************************************************************************

  -> This C++ program is to solve the towers of hanoi problem.
  -> Implemented using recursion.
  -> Works in Microsoft VC++ 6.0 , windows xp.
  -> Header files used 1)iostream.h

***************************************************************************/

#include<iostream.h>

void move(int n,char *s,char *i,char *d)
// s stands for source tower
// d stands for destination tower
// i stands for intermediate tower
{
 if(n>0)
 {
  move(n-1,s,d,i);
  // move n-1 disks from source to intermediate tower
  cout<<“disk “<<n<<” is moved from “<<s<<” to “<<d<<endl;
  // move the disk from to source to destination
  move(n-1,i,s,d);
  // move n-1 disks from intermediate to destination
 }
}

void main()
{
 cout<<“\n**********************************************************\n”;
 cout<<“This C++ program is to solve the towers of hanoi problem”;
 cout<<“\n**********************************************************\n”;
 cout<<“Enter the no. of disks “;
 int n;
 cin>>n;
 move(n,”source tower”,”intermediate tower”,”destination tower”);
}

Posted in linear data structures | Leave a Comment »

STACKS

Posted by Vinod on September 16, 2006

      Stacks

DEFINITION1:   Stack is an ordered collection of items into which new items may be inserted and from which items may be deleted at one end.

DEFINITION2: Stack is a linear list in which insertions and deletions take place at the same end.

The end at which the operations are taking place is called top

The other end is called bottom

Ex:

T<-top

J

K

S

F<-bottom

This is LIFO (Last-in-first-out) structure.

The insertion of element into stack is called push

The deletion of element from stack is called pop.

OVERFLOW:

This situation will come when the stack is implemented using an array.

If an element is pushed into the stack when the size of the stack greater than or equal to maximum size of the array, then we say that the stack is overflowing.

Underflow:

If deletion operation is performed on the stack with no elements then the stack is said to be underflowing .This occurs in both types of implementations of stack.

Algorithm for push operation:

Push(key,top):(Array implementation of stack)

1)If(top>=maximum size of the stack)

  i)Then print “Stack is overflowing”

2)Else

   i)Stack[top]=key;

  ii)top=top+1;

Algorithm for pop operation:

Pop():

1)if(top=0)

          1)print “The stack is underflowing”

2)else

          return stack[–top]

Applications of stack :

1)parenthesis matching

2)Towers of Hanoi

3)Rearranging rail road cars

4)Rat in a maze.

NOTE:

I am writing this notes by referring to the following reference books. The students who are new to data structures are being advised to refer to “CLASSICAL DATA STRUCTURES” by SAMANTHA.

References:

1) Data structures, Algorithms &Applications in c++   by SAHNI

2)classic data structures by  SAMANTHA

Posted in linear data structures, Uncategorized | Leave a Comment »

Kruskal ALgorithm

Posted by Vinod on August 11, 2006

//implemented using sets concept 

#include<iostream.h>
class kruskal
{
private:
 int n;
 int graph[10][10];
 int tree[10][10];
 int noe;
 int edges[100][4];
 int sets[100][10];
 int top[100];
public:
 void read_graph();
 void initialize_span_t();
 void sort_edges();
 void algorithm();
 int find_node(int );
 void print_min_span_t();
};

void kruskal::read_graph()
{
 cout<<“Enter the no. of nodes in the graph ::”;
 cin>>n;
 cout<<“Enter the adjacency matrix of the graph ::\n”;
 for(int i=1;i<=n;i++)
  for(int j=1;j<=n;j++)
   cin>>graph[i][j];
}

void kruskal::sort_edges()
{
 int i,j;
 /******* Initialize the edges *************/
 noe=0;
 for(i=1;i<=n;i++)
 {
  for(j=i;j<=n;j++)
  {
   if(graph[i][j]!=0)
   {
    noe++;
    edges[noe][1]=i;
    edges[noe][2]=j;
    edges[noe][3]=graph[i][j];
   }
  }
 }
 
 /*********** Sort the edges **************/
 
 for(i=1;i<=noe;i++)
 {
  for(j=i;j<=noe-1;j++)
  {
   if(edges[j][3]>edges[j+1][3])
   {
    int t=edges[j][1];
    edges[j][1]=edges[j+1][1];
    edges[j+1][1]=t;
    
    t=edges[j][2];
    edges[j][2]=edges[j+1][2];
    edges[j+1][2]=t;
    
    t=edges[j][3];
    edges[j][3]=edges[j+1][3];
    edges[j+1][3]=t;
   }
  }
 }
  
  /*********** Print the edges **************/

 cout<<endl;
 for(i=1;i<=noe;i++)
  cout<<edges[i][1]<<‘\t'<<edges[i][2]<<‘\t'<<edges[i][3]<<endl;
}

void kruskal::initialize_span_t()
{
 for(int i=1;i<=n;i++)
  for(int j=1;j<=n;j++)
   tree[i][j]=0;
}

void kruskal::algorithm()
{
 // ->make a set for each node
 for(int i=1;i<=n;i++)
 {
  sets[i][1]=i;
  top[i]=1;
 }

 for(i=1;i<=noe;i++)
 {
  int p1=find_node(edges[i][1]);
  int p2=find_node(edges[i][2]);

  cout<<p1<<“\t”<<p2<<endl;

  if(p1!=p2)
  {
   tree[edges[i][1]][edges[i][2]]=edges[i][3];
   tree[edges[i][2]][edges[i][1]]=edges[i][3];

   // Mix the two sets
   
   for(int j=1;j<=top[p2];j++)
   {
    top[p1]++;
    sets[p1][top[p1]]=sets[p2][j];
   }

   top[p2]=0;
  }
 }
}

int kruskal::find_node(int n)
{
 for(int i=1;i<=noe;i++)
 {
  for(int j=1;j<=top[i];j++)
  {
   if(n==sets[i][j])
    return i;
  }
 }
 return -1;
}
void kruskal::print_min_span_t()
{
 for(int i=1;i<=n;i++)
 {
  for(int j=1;j<=n;j++)
   cout<<tree[i][j]<<‘\t’;
  cout<<endl;
 }
}
int main()
{
 kruskal obj;
 obj.read_graph();
 obj.sort_edges();
 obj.initialize_span_t();
 obj.algorithm();
 obj.print_min_span_t();
 return 0;
}

Posted in graphs, minimum spanning tress | Leave a Comment »

topological sort

Posted by Vinod on July 13, 2006

/*
AUTHOR:B.VINOD KUMAR
“*/
using namespace std;
#include<iostream>
class graph
{
     private:
          int n;
   int data[20];
          int gptr[20][20];
     public:
          void create();
          void topological();
};
void graph::create()
{
        cout<<“enter how many elements :”;
        cin>>n;
 cout<<“enter data for the nodes:\n”;
 for(int i=1;i<=n;i++)
      cin>>data[i];
        cout<<“enter “<<n<<“x”<<n<<” adjacency matrix elements :\n”;
        int i,j;
        for(i=1;i<=n;i++)
         for(j=1;j<=n;j++)
          cin>>gptr[i][j];
}
void graph::topological()
{
        int flag;
        int i,j;
        int poset[20],included[20];
        for(i=1;i<=n;i++)
        {
         poset[i]=0;
         included[i]=false;
        }
        int k=1;
        flag=true;
        int zeroindegree;
 int c=1;
        while(flag==1)
        {
         for(i=1;i<=n;i++)
                {
          if(!included[i])
          {
           zeroindegree=true;
           for(j=1;j<=n;j++)
                                {
            if(gptr[j][i]>0)
                                      {
             zeroindegree=false;
             break;
            }
                                }
           if(zeroindegree)
           {
            included[i]=true;
            poset[k]=data[i];
            k=k+1;
            for(j=1;j<=n;j++)
            {
                                         gptr[i][j]=-1;
             gptr[j][i]=-1;
            }
                                        break;
           }
          }
                }
         if(i==n+1)
         {
   if(zeroindegree==false)
   {
          cout<<“Graph is not acyclic\n”;
                        return;
   }
   else
   {
            poset[k]=data[i-1];
            k=k+1;
                   flag=false;
   }
          }
     }
       cout<<“After topological sorting:\n”;
         for(i=1;i<=n;i++)
               cout<<poset[i]<<“\t”;
  cout<<endl;
}
int main()
{
     graph obj;
     obj.create();
     obj.topological();
     return 0;
}

Posted in graphs, Uncategorized | 2 Comments »

Heap Sort

Posted by Vinod on July 13, 2006

#include<stdio.h>
#include<iostream.h>
class heap
{
 double *a;
 int n,hsize;
 public:
 void swap(double& f,double& g);
 void bulit(int j);
 void heapsort(void);
 void heapify(int i);
friend istream & operator>>(istream &in,heap &x);
friend ostream & operator<<(ostream &out,heap &x);
};
 ostream & operator<<(ostream &out,heap &x)
{ out<<“\n THE SORTED ORDER IS:\n”;
 for(int i=1;i<=x.hsize;i++)
 out << x.a[i]<<”  “;
 out <<“\n”;
 return out;
 }
istream & operator>> (istream &in,heap &x)
{
 cout<<“\n ENTER THE NO:OF ELEMENTS TO BE INPUTED:”;
 in >>x.n;
 x.hsize=x.n;
 cout<<“\n ENTER “<<”  “<<x.n<<“THE NUMBERS TO SORTED:”;
 x.a=new double[x.hsize];
 for(int i=1;i<=x.n;i++)
 in >>x.a[i];
  cout<<“\n”;
 return in;
 }

void heap::swap(double& f,double& g)
{
  double temp;
  temp=f;
  f=g;
  g=temp;
}
void heap::heapify(int i)
{
  int l=2*i;
  int r=2*i+1;
  int large;
  if(a[r]>=a[l]&&l<=n&&r<=n)
  swap(a[l],a[r]);
  if(l<=n&&a[l]>a[i])
   large=l;
  else
   large=i;
  if(i!=large)
   {
    swap(a[i],a[large]);
    heapify(large);
   }
}
void heap::bulit(int j)
{
 for(int i=j/2;i>=1;i–)
 heapify(i);
}
void heap::heapsort()
{
  cin>>*this;
  bulit(hsize);
  for(int i=hsize;i>=1;i–)
  {
   bulit(i);
   heapify(1);
   swap(a[i],a[1]);
   n–;
  }
  cout<<*this;
  delete []a;
}
int main()
{
  heap h;
  h.heapsort();
  return 0;
}

Posted in sort | Leave a Comment »

Binary Tree Traversals

Posted by Vinod on May 29, 2006

Binary TreeThis program is for creating and traversing a binary tree in preorder,inorder,postorder using recursion and level order using iteration

Posted in Trees | 1 Comment »

sorting

Posted by Vinod on May 29, 2006

Sorting Algorithmssorting techniques

Posted in c++ | Leave a Comment »

ADT

Posted by Vinod on May 29, 2006

ADT This is about abstract data types

Posted in c++ | Leave a Comment »