This document provides instructions for an assignment on data and file structures lab. It includes two questions to write programs in C language on:
1. Writing an algorithm and program to convert a tree to a binary tree.
2. Writing an algorithm and program for multiplication of two sparse matrices using pointers.
The document provides detailed algorithms and C code implementations for converting a binary tree to a binary search tree and representing and multiplying sparse matrices using multilinked data structures with pointers.
Data and File Structures Lab Assignment on Converting Binary Tree to Binary Search Tree
1. Course Code
:
BCSL-033
Course Title
:
Data and File Structures Lab
Assignment Number
:
BCA(III)-033/Assign/13
Maximum Marks
:
50
Weightage
:
25%
Last Dates for Submission :
15th October,2013 (For July 2013 Session)
15th April, 2014 (For January 2014 Session)
This assignment has two questions, each of 20 marks.10 marks are for viva-voce.
Attach input and output of the program to the assignment. Write programs in ‘C’
language.
Question 1:
(20 marks)
Write algorithm and program for the conversion of a Tree to a Binary Tree.
Ans :Following is a 3 step solution for converting Binary tree to Binary Search Tree.
1) Create a temp array arr[] that stores inorder traversal of the tree. This step takes
O(n) time.
2) Sort the temp array arr[]. Time complexity of this step depends upon the sorting
algorithm. In the following implementation, Quick Sort is used which takes (n^2) time.
This can be done in O(nLogn) time using Heap Sort or Merge Sort.
3) Again do inorder traversal of tree and copy array elements to tree nodes one by
one. This step takes O(n) time.
Following is C implementation of the above approach. The main function to convert is
highlighted in the following code.
2. /* A program to convert Binary Tree to Binary Search Tree */
#include<stdio.h>
#include<stdlib.h>
/* A binary tree node structure */
struct node
{
int data;
struct node *left;
struct node *right;
};
/* A helper function that stores inorder traversal of a tree rooted
with node */
void storeInorder (struct node* node, int inorder[], int *index_ptr)
{
// Base Case
if (node == NULL)
return;
/* first store the left subtree */
storeInorder (node->left, inorder, index_ptr);
/* Copy the root’s data */
inorder[*index_ptr] = node->data;
(*index_ptr)++; // increase index for next entry
/* finally store the right subtree */
storeInorder (node->right, inorder, index_ptr);
}
/* A helper function to count nodes in a Binary Tree */
int countNodes (struct node* root)
{
if (root == NULL)
return 0;
3. return countNodes (root->left) +
countNodes (root->right) + 1;
}
// Following function is needed for library function qsort()
int compare (const void * a, const void * b)
{
return ( *(int*)a – *(int*)b );
}
/* A helper function that copies contents of arr[] to Binary Tree.
This functon basically does Inorder traversal of Binary Tree and
one by one copy arr[] elements to Binary Tree nodes */
void arrayToBST (int *arr, struct node* root, int *index_ptr)
{
// Base Case
if (root == NULL)
return;
/* first update the left subtree */
arrayToBST (arr, root->left, index_ptr);
/* Now update root’s data and increment index */
root->data = arr[*index_ptr];
(*index_ptr)++;
/* finally update the right subtree */
arrayToBST (arr, root->right, index_ptr);
}
// This function converts a given Binary Tree to BST
void binaryTreeToBST (struct node *root)
{
// base case: tree is empty
if(root == NULL)
return;
4. /* Count the number of nodes in Binary Tree so that
we know the size of temporary array to be created */
int n = countNodes (root);
// Create a temp array arr[] and store inorder traversal of tree in arr[]
int *arr = new int[n];
int i = 0;
storeInorder (root, arr, &i);
// Sort the array using library function for quick sort
qsort (arr, n, sizeof(arr[0]), compare);
// Copy array elements back to Binary Tree
i = 0;
arrayToBST (arr, root, &i);
// delete dynamically allocated memory to avoid meory leak
delete [] arr;
}
/* Utility function to create a new Binary Tree node */
struct node* newNode (int data)
{
struct node *temp = new struct node;
temp->data = data;
temp->left = NULL;
temp->right = NULL;
return temp;
}
/* Utility function to print inorder traversal of Binary Tree */
void printInorder (struct node* node)
{
if (node == NULL)
return;
5. /* first recur on left child */
printInorder (node->left);
/* then print the data of node */
printf(“%d “, node->data);
/* now recur on right child */
printInorder (node->right);
}
/* Driver function to test above functions */
int main()
{
struct node *root = NULL;
/* Constructing tree given in the above figure
10
/
30 15
/
20
5 */
root = newNode(10);
root->left = newNode(30);
root->right = newNode(15);
root->left->left = newNode(20);
root->right->right = newNode(5);
// convert Binary Tree to BST
binaryTreeToBST (root);
printf(“Following is Inorder Traversal of the converted BST: n”);
6. printInorder (root);
return 0;
}
Output:
Following is Inorder Traversal of the converted BST:
5 10 15 20 30
Question 2:
(20 marks)
Write algorithm and program for multiplication of two Sparse Matrices using Pointers.
Ans :- algorithen
A useful application of linear list is the representation of matrices that contain a
preponderance of zero elements. These matrices are called sparse matrices. Consider
the matrix
0 0 6 0 9 0 0
2 0 0 7 8 0 4
10 0 0 0 0 0 0
0 0 12 0 0 0 0
0 0 0 0 0 0 0
0 0 0 3 0 0 5
Of the 42 elements in the 6*7 matrix, only 10 are nonzero. One of the basic methods
of storing is to store nonzero elements in a one-dimensional array and to identify
each array element with row and column indices as shown in figure (a). The ith
element of vector A is the matrix element with row and column indices ROW[i] and
COLUMN[i]. Matrix elements are stored in row major order with zero elements
removed. In a more efficient representation shown in figure (b), the ROW vector is
changed so that its ith element is the index to the first of column indices for the
elements in row i of the matrix.
ROW COLUMN A
1 1
3
6
2 1
5
9
3 2
1
2
7. 4 2
5 2
6 2
7 3
8 4
9 6
10 6
figure (a)
COLUMN
1
3
ROW 2
1
1
2
3
3
7
4
8
5
0
6
9
row
number
column
number
4
5
7
1
3
4
7
7
8
4
10
12
3
5
6
5
9
A
3
4
5
6
7
8
1
4
5
7
1
3
9
10
4
7
2
7
8
4
10
12
3
5
figure (b)
An algorithm for adding 2 matrices that are represented in figure(b) is given below:
Algorithm MATRIX_ADDITION. Given sparse matrices A and B represented by vectors
A and B with row and column indices AROW and ACOL, BROW and BCOL, respectively,
it is required to form the matrix sum C=A+B. C must be represented in the same
manner A and B, so CROW and CCOL are formed. A and B have the same dimensions,
M*N, and contain R and S nonzero elements, respectively. The number of nonzero
elements in C on completion of the algorithm is T. Auxiliary variable l is used to index
the rows of the matrices and J and K index the matrix elements in vectors A and B,
respectively. Variables SUM and COLUMN are used to contain each new element for
matrix C and column position.
1. Initialize
l=1
8. T=0
2. Scan each row
Repeat thru step 9 while l<=M
3. Obtain row indices and starting positions of next rows
J=AROW[l]
K=BROW[l]
CROW[l]=T+1
AMAX=BMAX=0
If l<M
then Repeat for P=l+1, l+2, ……M while AMAX=0
If AROW[P]/=0
then AMAX=AROW[P]
Repeat for P=l+1, l+2,…….M while BMAX=0
If BROW[P]/=0
then BMAX=BROW[P]
If AMAX=0
then AMAX=R+1
If BMAX=0
then BMAX=S+1
4. Scan columns of this row
Repeat thru step 7 while J/=0 and K/=0
5. Elements in same column?
If ACOL[J]=BCOL[K]
then SUM=A[J]+B[K]
COLUMN=ACOL[J]
J=J+1
K=K+1
else If ACOL[J]<BCOL[K]
then SUM=A[J]
COLUMN=ACOL[J]
J=J+1
else SUM=B[K]
COLUMN=BCOL[K]
K=K+1
6. Add new elements to sum of matrices
If SUM/=0
9. then T=T+1
C[T]=SUM
CCOL[T]=COLUMN
7. End of either row?
If J=AMAX
then J=0
If K=BMAX
then K=0
8. Add remaining elements of a row
If J=0 and K/=0
then repeat while K<BMAX
T=T+1
C[T]=B[K]
CCOL[T]=BCOL[K]
K=K+1
else if K=0 and J/=0
then repeat while J<AMAX
T=T+1
C[T]=A[J]
CCOL[T]=ACOL[J]
J=J+1
9. Adjust index to matrix C and increment row index
If T<CROW[l]
then CROW[l]=0
l=l+1
10. Finished
Exit
For each pair of correspondin rows in matrices A and B, steps 3 to 9 are executed to
add matrix elements from those rows. When J or K is zero, the nonzero elements in
the row of matrix A or B, respectively, have all been accounted for. When both J and K
are zero, the algorithm can proceed to add the next rows of the matrices. If J or K are
nor initially zero, they are set to zero when they reach the values AMAX or BMAX,
respectively. AMAX and BMAX are the positions in the ACOL and A and BCOL and B
vectors where the next row starts. However, if there is no next row, AMAX and BMAX
have values R+1 and S+1, respectively.
10. Steps 5 to 7 inclusive perform the required additions of matrix elements. Step 6
checks for an element having a value zero before adding it to matrix C. If no elements
are added to row 1 of matrix C, then CROW[l] is set to zero in step 9.
A basic node structure called MATRIX_ELEMENT as depicted in the below figure is
required to represent sparse matrices. The V, R and C fields of one of those nodes
contain the value, row, and column indices, respectively, of one matrix element. The
fields LEFT and UP are pointers to the next element in a circular list containing matrix
elements for a row or column. LEFT points to the node with the next smallest column
subscript, and UP points to the node with the next smallest row subscript.
_____________
| LEFT
UP|
|V | R | C|
A circular list represent each row and column. A column’s list can share nodes with
one or more of the row’s list. Each row and column list has a head node such that
more efficient insertion and deletion algorithms can be implemented. The head node
of each row list contains 0 in the C field. The head node of each column list has 0 in
the R field. The row head nodes are pointed to by respective elements in the array of
pointers AROW. Elements of ACOL point to the column head nodes. A row or column
without nonzero elements is represented by a head node whose LEFT and UP field
points to itself.
In scanning a circular list we encount matrix elements in order of decreasing row or
column subscripts. This is used to simplify the insertion of new nodes to the structue.
We assume that new nodes being added to a matrix are usually ordered by ascendingrow subscript and ascending-column subscript. A new node is inserted following the
head node all the time and no searching of the list is necessary.
Algorithm for constructing a multilinked structue representing a matrix is given below.
It is assumed that input records for the algorithm consist of row, column, and nonzero
matrix-element values in arbitrary order.
Algorithm CONSTRUCT_MATIX. It is required to form a multilinked representation of a
matrix using the MATRIX-ELEMENT node structure. The matrix dimensions M and N,
representing the number of rows and columns are known before execution
of algorithm. Arrays AROW and ACOL contain pointers to the head nodes of the
circular lists. X and Y are used as auxiliary pointers. A row index, column index, and
value of a matrix element are read into variables ROW, COLUMN, and VALUE.
1. Initialize matix structures
repeat for l=1,2,…..M
ACROW[l]=MATRIX_ELEMENT
C(AROW[l])=0
11. LEFT(AROW[l]=AROW[l]
repeat for l=1,2……N
ACOL[l]=MATRIX_ELEMENT
R(ACOL[l]=0
UP(ACOL[l]=ACOL[l]
2. Loop until there is no more input
repeat thru step 7 until input records are exhausted
3. Obtain the next matrix element
read(ROW, COLUMN, VALUE)
4. Allocate and initialize a node
P=MATRIX_ELEMENT
R(P)=ROW
C(P)=COLUMN
V(P)=VALUE
5. Find new node’s position in row list
Q=AROW[R(P)]
repeat while C(P)<C(LEFT(Q))
Q=LEFT(Q)
LEFT(P)=LEFT(Q)
LEFT(Q)=P
6. Find new node’s position in column list
Q=ACOL[C(P)]
repeat while R(P)<R(UP(Q))
Q=UP(Q)
UP(P)=UP(Q)
UP(Q)=P
7. Finished
Exit
In step 1, the required head nodes are allocated and initialized. For each ROW,
COLUMN, and VALUE triplet subsequently read, a node is allocated and initialized.
Step 5 and 6 insert the new node in the appropriat row and column lists.
When 2 matrices A and B are multiplied to form matrix C, its necessary that the
number of columns in A equal the number of rows in B. If A has m rows and n
columns, and B has n rows and t columns, then the product matrix C will have m rows
and t columns. An algorithm for matrix multiplication is given below.
12. Algorithm MATRIX_MULTIPLICATION. Give the pointer arrays AROW, ACOL, BROW,
AND BCOL pointing to multilinked representations of sparse matrices A and B with
dimensions M*N and N*T, its required to form the representation of the product
matrix C=A*B. Pointer arrays CROW and CCOL are used to point to rows and columns
of the matrix C, which has dimensions M*T. Variables l and j are used to count the
rows of matrix A and the columns of matrix B. A and B are used as pointers for
scanning the rows of matrix A and columns of matrix B. P is an auxiliary pointer.
1. Set up head nodes for row lists
repeat for l=1,2,…..M
CROW[l]=MATRIX_ELEMENT
C(CROW[l]=0
LEFT(CROW[l]=CROW[l]
2. Set up head nodes for column lists
repeat for j=1,2,…..T
CCOL[j]=MATRIX_ELEMENT
R(CCOL[j]=CCOL[j]
3. Use M rows of matrix A
repeat thru step 7 for l=1,2,……M
4. Use T columns of matrix B
repeat thru step 7 for j=1,2,……T
5. Initialize for scanning row l of matrix A and column j of matrix B
A=LEFT(AROW[l])
B=UP(BCOL[j])
PRODUCT=0
6. Move pointers as necessary and multiply matching elements
repeat while R(B)/=0 and C(A)/=0
if C(A)>R(B)
then A=LEFT(A)
else if R(B)>C(A)
then B=UP(B)
else PRODUCT=PRODUCT+V(A)*V(B)
A=LEFT(A)
B=UP(B)
7. If product is nonzero add it to matrix C
if PRODUCT/=0
then P=MATRIX_ELEMENT
13. R(P)=l
C(P)=j
V(P)=PRODUCT
LEFT(P)=LEFT(CROWN[l])
UP(P)=UP(CCOL[j])
LEFT(CROWN[l])=P
UP(CCOL[j])=P
8. Finished
Exit
Steps 1 and 2 initialize the head nodes for the product matrix C. Steps 3 and 4 provide
repetitions necessary to multiply each row of matrix A by each column of matrix B in
steps 5 to 7, inclusively. Step 5 initializes pointers A and B to scan the circular lists of
row l of matrix A and column j of matrix B. The variable PRODUCT is initialized in this
step, and it will be used to total the products of corresponding row and column
elements.
In step 6, note that row l and column j are being scanned in order of decreading
column and row subscripts. If the column subscript and the row subscript of the
nodes pointed to by A and B, resp. are not equal, then one pointer is moved to the
next node in the circular list. If those row and column subscripts are equal, however,
then the variable PRODUCT is updated and both pointers A and B are changed to
point to the next elements in each list. When the head node in either list is reached,
the required product of row l and column j has been computed.
Step 7 allocates and initializes a new node if PRODUCT is nonzero. Because rows and
columns are being scanned according to increasing subscript values, and because
pointes in the nodes point left and up in the list structure, the new node can be
inserted as successor to the head nodes of row l and column j.
Program :#include <stdio.h>
#include <conio.h>
#include <alloc.h>
#define MAX1 3
#define MAX2 3
#define MAXSIZE 9
#define BIGNUM 100
struct sparse
{
int *sp ;
int row ;
15. int n, i ;
/* allocate memory */
p -> sp = ( int * ) malloc ( MAX1 * MAX2 * sizeof ( int ) ) ;
/* add elements to the array */
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
printf ( “Enter element no. %d:”, i ) ;
scanf ( “%d”, &n ) ;
* ( p -> sp + i ) = n ;
}
}
/* displays the contents of the matrix */
void display ( struct sparse s )
{
int i ;
/* traverses the entire matrix */
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % MAX2 == 0 )
printf ( “n” ) ;
printf ( “%dt”, * ( s.sp + i ) ) ;
}
}
/* counts the number of non-zero elements */
int count ( struct sparse s )
{
int cnt = 0, i ;
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
if ( * ( s.sp + i ) != 0 )
cnt++ ;
}
return cnt ;
}
/* creates an array that stores information about non-zero elements */
void create_tuple ( struct sparse *p, struct sparse s )
{
int r = 0 , c = -1, l = -1, i ;
/* get the total number of non-zero elements
16. and add 1 to store total no. of rows, cols, and non-zero values */
p -> row = count ( s ) + 1 ;
/* allocate memory */
p -> sp = ( int * ) malloc ( p -> row * 3 * sizeof ( int ) ) ;
/* store information about
total no. of rows, cols, and non-zero values */
* ( p -> sp + 0 ) = MAX1 ;
* ( p -> sp + 1 ) = MAX2 ;
* ( p -> sp + 2 ) = p -> row – 1 ;
l=2;
/* scan the array and store info. about non-zero values in the 3-tuple */
for ( i = 0 ; i < MAX1 * MAX2 ; i++ )
{
c++ ;
/* sets the row and column values */
if ( ( ( i % MAX2 ) == 0 ) && ( i != 0 ) )
{
r++ ;
c=0;
}
/* checks for non-zero element row, column and non-zero element value is assigned
to the matrix */
if ( * ( s.sp + i ) != 0 )
{
l++ ;
* ( p -> sp + l ) = r ;
l++ ;
* ( p -> sp + l ) = c ;
l++ ;
* ( p -> sp + l ) = * ( s.sp + i ) ;
}
}
}
/* displays the contents of the matrix */
void display_tuple ( struct sparse s )
{
int i, j ;
/* traverses the entire matrix */
printf ( “nElements in a 3-tuple: n” ) ;
j = ( * ( s.sp + 2 ) * 3 ) + 3 ;
17. for ( i = 0 ; i < j ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % 3 == 0 )
printf ( “n” ) ;
printf ( “%dt”, * ( s.sp + i ) ) ;
}
printf ( “n” ) ;
}
/* carries out addition of two matrices */
void addmat ( struct sparse *p, struct sparse s1, struct sparse s2 )
{
int i = 1, j = 1, k = 1 ;
int elem = 1 ;
int max, amax, bmax ;
int rowa, rowb, cola, colb, vala, valb ;
/* get the total number of non-zero values from both the matrices */
amax = * ( s1.sp + 2 ) ;
bmax = * ( s2.sp + 2 ) ;
max = amax + bmax ;
/* allocate memory for result */
p -> result = ( int * ) malloc ( MAXSIZE * 3 * sizeof ( int ) ) ;
while ( elem <= max )
{
/* check if i < max. non-zero values
in first 3-tuple and get the values */
if ( i <= amax )
{
rowa = * ( s1.sp + i * 3 + 0 ) ;
cola = * ( s1.sp + i * 3 + 1 ) ;
vala = * ( s1.sp + i * 3 + 2 ) ;
}
else
rowa = cola = BIGNUM ;
/* check if j < max. non-zero values in secon 3-tuple and get the values */
if ( j <= bmax )
{
rowb = * ( s2.sp + j * 3 + 0 ) ;
colb = * ( s2.sp + j * 3 + 1 ) ;
valb = * ( s2.sp + j * 3 + 2 ) ;
18. }
else
rowb = colb = BIGNUM ;
/* if row no. of both 3-tuple are same */
if ( rowa == rowb )
{
/* if col no. of both 3-tuple are same */
if ( cola == colb )
{
/* add tow non-zero values
store in result */
* ( p -> result + k * 3 + 0 ) = rowa ;
* ( p -> result + k * 3 + 1 ) = cola ;
* ( p -> result + k * 3 + 2 ) = vala + valb ;
i++ ;
j++ ;
max– ;
}
/* if col no. of first 3-tuple is < col no. of second 3-tuple, then add info. as it is to result
*/
if ( cola < colb )
{
* ( p -> result + k * 3 + 0 ) = rowa ;
* ( p -> result + k * 3 + 1 ) = cola ;
* ( p -> result + k * 3 + 2 ) = vala ;
i++ ;
}
/* if col no. of first 3-tuple is > col no. of second 3-tuple, then add info. as it is to result
*/
if ( cola > colb )
{
* ( p -> result + k * 3 + 0 ) = rowb ;
* ( p -> result + k * 3 + 1 ) = colb ;
* ( p -> result + k * 3 + 2 ) = valb ;
j++ ;
}
k++ ;
}
/* if row no. of first 3-tuple is < row no. of second 3-tuple, then add info. as it is to
result */
19. if ( rowa < rowb )
{
* ( p -> result + k * 3 + 0 ) = rowa ;
* ( p -> result + k * 3 + 1 ) = cola ;
* ( p -> result + k * 3 + 2 ) = vala ;
i++ ;
k++ ;
}
/* if row no. of first 3-tuple is > row no. of second 3-tuple, then add info. as it is to
result */
if ( rowa > rowb )
{
* ( p -> result + k * 3 + 0 ) = rowb ;
* ( p -> result + k * 3 + 1 ) = colb ;
* ( p -> result + k * 3 + 2 ) = valb ;
j++ ;
k++ ;
}
elem++ ;
}
/* add info about the total no. of rows, cols, and non-zero values that the resultant
array contains to the result */
* ( p -> result + 0 ) = MAX1 ;
* ( p -> result + 1 ) = MAX2 ;
* ( p -> result + 2 ) = max ;
}
/* displays the contents of the matrix */
void display_result ( struct sparse s )
{
int i ;
/* traverses the entire matrix */
for ( i = 0 ; i < ( * ( s.result + 0 + 2 ) + 1 ) * 3 ; i++ )
{
/* positions the cursor to the new line for every new row */
if ( i % 3 == 0 )
printf ( “n” ) ;
printf ( “%dt”, * ( s.result + i ) ) ;
}
}
/* deallocates memory */
20. void delsparse ( struct sparse *p )
{
if ( p -> sp != NULL )
free ( p -> sp ) ;
if ( p -> result != NULL )
free ( p -> result ) ;
}