+ All Categories
Home > Documents > Data Structures 14a

Data Structures 14a

Date post: 06-Nov-2015
Category:
Upload: nilu
View: 229 times
Download: 0 times
Share this document with a friend
Description:
good ppt
52
DATA STRUCTURES 14 A - E Lower Triangular Matrix, 14A Polynomial Representation, 14A Dynamic Memory Allocation (Calloc & Malloc), 14A &14B Stacks, 14C Notations, 14D Circular Queues 14E Priority Queues, 14E
Transcript
  • DATA STRUCTURES

    14 A - E

    Lower Triangular Matrix, 14A Polynomial Representation, 14ADynamic Memory Allocation (Calloc & Malloc), 14A &14B Stacks, 14C Notations, 14DCircular Queues 14EPriority Queues, 14EDeques 14E

  • DATA STRUCTURES Lower Triangular Matrix

    Lower & Upper Triangular Matrix

  • DATA STRUCTURES Lower Triangular MatrixLower Triangular Matrix: Sparse matrix with all entries above diagonal being zero. For example a1100000a21a220000a31a32a33000 - ----- 0-------an1an2an3ann

  • DATA STRUCTURES Lower Triangular MatrixThis lower triangular matrix can be stored as single dimensional array B[m] where m is equal to the total number of elements present below and on the main diagonal.Thus B=[ a11 a21 a22 a31 a32 a33 a41 a42 a43 a44 . ai1 ai2 ai3 aij aii a(i+1)1 a(i+1)2 .a(i+1)(i+1) an1 an2an3an4ann ]I have written in separate lines to make it easily understandable.

  • DATA STRUCTURES Lower Triangular Matrixa11000 0 0a21a2200 0 0a31a32a330 0 0 - ----- 0 0------- 0 0Up to row (i-1) has 1+2++(i-1)=(i-1)*i/2 elements ai1 ai2 ai3 --aii0 0 0Up to this row [a11 to aii] has 1+2++i=i*(i+1)/2=(i-1)*i/2 +i elementsThus up to aij has 1+2++(i-1)+j=(i-1)*i/2+j elements-------an1an2an3 ann

  • DATA STRUCTURES Lower Triangular MatrixIn this matrix a[i,j] = 0 for i < j.This lower triangular matrix can be stored as single dimensional array B[m] where m is equal to the total number of elements present below and on the main diagonal.Now we want the function that computes us the integer L in terms of i and j, where B[L] = A[i,j].Obviously, L represents the number of elements in the list up to and including A[i,j]Now, there are 1 + 2 + 3 + (i 1) = (i 1)*i /2 elements in the rows above A[i,j] and there are j elements in row i up to and including A[i,j] j j and L is related to i & j by the above equation and = 0 where i < j.

  • DATA STRUCTURES Lower Triangular MatrixUpper Triangular Matrix: Sparse matrix with all entries below diagonal being zero. For example a11a12a13a14a1n0a22a23a24a2n00a33a34a3n0 0 0a44-- a4n-------000000ann

  • DATA STRUCTURES Lower Triangular MatrixThe sum of two upper triangular matrices is upper triangular. The product of two upper triangular matrices is upper triangular. The inverse of an invertible ** upper triangular matrix is upper triangular. The product of an upper triangular matrix by a constant is an upper triangular matrix.[ Same are true for lower triangular matrices. ][** Invertible matrix means that it is possible to calculate an inverse to the matrix. ]

  • DATA STRUCTURES Lower Triangular MatrixUnitriangular matrix --- If the entries on the main diagonal of a (upper or lower) triangular matrix are all 1, the matrix is called (upper or lower) unitriangular OR unit (upper or lower) triangular OR normed (upper or lower) triangular matrices. [ NB unit triangular matrix is not the same as the unit matrix. ]The identity matrix is the only matrix which is both upper and lower unitriangular.

  • DATA STRUCTURES Lower Triangular MatrixAn atomic (upper or lower) triangular matrix is a special form of unitriangular matrix, where all of the off-diagonal entries are zero, except for the entries in a single column. [= Gauss matrix = Gauss transformation matrix]Example . 1 0 0 0 0 0 1 0 0 0 0 3 1 0 0 0 5 0 1 0 0 7 0 0 1The inverse of an atomic triangular matrix is an atomic triangular matrix.

  • DATA STRUCTURES Lower Triangular MatrixExercise: On similar approach, try and find out the value of L for such Upper Triangular Matrices. [ans. (2n i)*(i 1)/2 + j ]

  • DATA STRUCTURES Lower Triangular MatrixA strictly upper triangular matrix is an upper triangular matrix having 0s along the diagonal as well i.e. aij=0 for i>=j.

    A strictly lower triangular matrix is a lower triangular matrix having 0s along the diagonal as well i.e. aij=0 for i

  • DATA STRUCTURES Polynomial Representation

    Polynomial Representation

  • DATA STRUCTURES Polynomial RepresentationRepresentation of polynomials using arrays. Sometimes we will need to evaluate several polynomial expressions & perform basic arithmetic operations like Addition, multiplication etc. on them. So we need a method to represent a polynomial . The easiest way to represent a polynomial of degree n is by storing the coefficient of (n+1) terms of a polynomial in an array. An expression x+4x2-7x5 is a polynomial of degree 5. [ coefficients 0, 1, 4, 0, 0, -7 OR -7, 0, 0, 4, 1, 0 ]

  • DATA STRUCTURES Polynomial Representation All the elements of this array has two values, coefficient and exponent. We may also assume that exponent of each successive term is less than that of the previous term. Once we build an array for the polynomials, we can use it toperform various operations including additions and multiplications. A single dimensional array is used to represent a single variable polynomial. The index of such an array can be considered as an exponent and the coefficient can be stored at that particular index.

  • DATA STRUCTURES Polynomial RepresentationThe polynomial expression 3x4 +5x3+ 6x2 +10x -14 can be stored in a single dimensional array.

    INDEX 0 1 2 3 4 5 6Coeffs of the polynomial -14 10 6 5 3 --- ----OR .This method has some problems, specially when we have very large exponents , say X 1111 in the polynomial. We have to define an array of size 1112. Scanning and processing of this array will be time consuming.The wastage of space is another issue.

  • DATA STRUCTURES Polynomial RepresentationWe may not be in a position to decide the size of the array. We may have to change the array size etc. and recompile the program and redo the testing of it.Thus this representation of a polynomial is suitable only if the upper limit of exponential value and the number of coefficients are quite close.

  • DATA STRUCTURES Polynomial RepresentationAddition of polynomials:-Add 2 polynomials A & B ; store the result in C.And i, j, k represent the pointers to the polynomials A, B, C and arrays respectively.ALGORITHM:--Set i, j & k to point to the first term in A, B & C.Read n1 & n2 = no of terms in A & B.While i < n1 and j < n2 then a) if exp at ith posn of A = exp of jth posn of B, then C at Kth posn = coeff of A at ith posn + coeff of B at jth posn. Increment I,j,k to point to the next position in A,B,C b) else

  • DATA STRUCTURES Polynomial Representation b) elseIf exp posn i> exp posn j in B then Copy coeff at ith posn from A to coeff at kth posn in CIncrement i, k elseCopy coeff at jth posn from B into coeff at posn k in CIncrement j, k pointers to point to the next position in B and C NOW YOU PROCEED

  • DATA STRUCTURES Polynomial RepresentationPolynomial Representation:Representation 1: int degree;/* degree
  • DATA STRUCTURES Polynomial RepresentationRepresentation 2: int degree; float *coef;Then within the program create array of coef as below: coef = (float *) calloc (degree + 1, sizeof(float));[ If these are to be revised calloc, malloc, free, realloc;let us go thru next few slides. ]Exercise: Write a C program to receive the degree and coefficients of a polynomial 7x4 - 3.5x2 + 28.9x 9 and print it in the form 7x^4 3.5x^2 + 28.9x 9

  • DATA STRUCTURES Dynamic Memory Allocation.

    Dynamic Memory Allocation. In C language the no. of elements in an array is to be specified before compilation. The process of allocating memory at run time is known as Dynamic Memory Allocation.There are 4 library routines under Memory Management Functions "that can be used for allocating and freezing memory at run (execution) time. These provides the above facility in C language.Memory Allocation Functions:---1. malloc() Allocates requested size of bytes in one block, & returns a pointer to the first byte of allocated space.

  • DATA STRUCTURES Dynamic Memory Allocation.Memory Allocation Functions:---malloc( ) Allocates requested size of bytes in one block, & returns a pointer to the first byte of allocated space. ptr =(cast type*) malloc (byte-size);e.g. x=(int*) malloc (100 * sizeof(int) );On successful execution of this statement, a memory space equivalent to 100 times the size of an int bytes is reserved & the address of the first byte of the memory allocated is assigned to the pointer x of type int.OR cptr = (char*)malloc(10); Allocates 10 bytes of space for the pointer cptr of type char. Cptr ----------| Address of | 10 bytes of spaceFirst byte | | | | | | | | | | |

  • DATA STRUCTURES Dynamic Memory Allocation.calloc( ) Allocates multiple blocks of memory storage, each of same size, initialized to zero, --- a pointer to the 1st byte of allocated space is returned. Mainly for derived data types e.g. arrays & structures. If pointer is NULL enough space is not available.. ptr = (cast-type*) calloc (n, elem-size); n blocks each of size elem-size bytes. all bytes are set to zero. a pointer to the first byte of the allocated region is returned.

  • DATA STRUCTURES Dynamic Memory Allocation. struct student{Char name[25];Float age;Long int id_num;};Typedef struct student record;Record *st_ptr;Int class_size = 30;St_ptr=(record*)calloc(class_size, sizeof(record));Record is of type struct student with 3 members; name, age, id_num.The calloc allocates memory to hold 30 such records.Before using st_ptr we are to be sure that the requested memory has been successfully allocated.

  • DATA STRUCTURES Dynamic Memory Allocation.If (st_ptr == NULL){ Printf(insufficient memory); Exit(1);}

  • DATA STRUCTURES Dynamic Memory Allocation.free(ptr)Frees space indicated by the pointer.This space must have been created by malloc or calloc.

    4. Realloc reallocation of memory.We can change the memory size already allocated. Say ptr = malloc(size);We can reallocate space by the statement ptr= realloc(ptr,newsize);The new memory block may or may not return at the same place as the first time. it will move the contents of the old block to the new block, keeping these intact.But if additional memory space is not available it returns a NULL pointer and the original block is freed(lost).

  • DATA STRUCTURES Dynamic Memory Allocation.EXERCISE:--Write a program to store a character string in a block of memory space created by malloc and then modify the same to store a larger string.

  • DATA STRUCTURES Polynomial Representation#include #include #include main() { int deg, i; float *cf;/*Write a C program to receive the degree and coefficients of a polynomial7x4 - 3.5x2 + 28.9x 9 & print it in the form 7x^4 3.5x^2 + 28.9x 9 */ printf("\nEnter degree: "); scanf("%d", &deg);

    cf = (float *) calloc (deg + 1, sizeof(float));

    for (i = 0; i < deg; i++){ printf("\nEnter coeff (%d): ", i); scanf("%f", (cf + i)); } printf("\n"); for (i = 0; i < deg; i++){ if (i > 0) if (*(cf + i) > 0.0) printf("+"); if (*(cf + i) == 0.0); else printf("%2.2fx^%d", *(cf + i), (deg - i)); } getch();}Here also space is wasted, for example if we have a polynomial as x1111 + 1

  • DATA STRUCTURES Polynomial Representation#include #include #include main() { int deg, i; float *cf;/*Write a C program to receive the degree and coefficients of a polynomial7x4 - 3.5x2 + 28.9x 9 & print it in the form 7x^4 3.5x^2 + 28.9x 9 */ printf("\nEnter degree: "); scanf("%d", &deg); cf = (float *) calloc (deg + 1, sizeof(float));

  • DATA STRUCTURES Polynomial Representation for (i = 0; i < deg; i++){ printf("\nEnter coeff (%d): ", i); scanf("%f", (cf + i)); } printf("\n"); for (i = 0; i < deg; i++){ if (i > 0) if (*(cf + i) > 0.0) printf("+"); if (*(cf + i) == 0.0); else printf("%2.2fx^%d", *(cf + i), (deg - i)); } getch(); }Here also space is wasted, if we have a polynomial as x1111 + 1

  • DATA STRUCTURES Polynomial RepresentationRepresentation 3:struct term { float coef; int exp; }; struct polynomial {int Start, Finish; };static struct term termArray[MAXTERM];static int free;This way say two polynomials A(x) = 5x^6 + 3x^2 + 7 and B(x) = 7x^3 10 can be stored as shown overleaf:

  • DATA STRUCTURES Polynomial Representation

    Col 0 1 2 3 4 5 A.Start A.Finish B.Start B.Finish freeCoef 5 3 7 7 -10 exp 6 2 0 3 0 col 0 1 2 3 4 5

  • DATA STRUCTURES Polynomial RepresentationExercise: Compare advantages and disadvantages of Representation 2 and Representation 3.

  • DATA STRUCTURES Polynomial RepresentationExercise: Compare advantages and disadvantages of Representation 2 and Representation 3.Representation 3 is definitely superior when many zero terms are present, for example A(x) = 2x^1000 + 1. Only 6 unit of spaces will be required four for table and two for start and finish.When all terms are nonzero, the Representation 3 uses about twice as much space as Representation 2.Representation 3 is preferable, when we dont know before hand about nonzero terms.

  • DATA STRUCTURES Polynomial RepresentationExercise: Write a C program to take two polynomials coefficients and exponent values and store them in one array. Print both the polynomials.

  • DATA STRUCTURES Polynomial Representation#include #define MAXTERM 20/* Data StructurePolynomial representation 1 */struct term { int cf; int exp;};

    struct poly { int Start, Finish;};

    static int free;static struct term termArray[MAXTERM];

    main() {

    int i, j, nos, end; struct poly A, B; free = 0;

    /* Create polynomials */ printf("\nEnter no of terms in polynomial A: "); scanf("%d", &nos);

    A.Start = free; for (i = A.Start; i < nos; i++) { printf("\nEnter coeff. %d: ", i+1); scanf("%d", &termArray[i].cf); printf("\nEnter exp. %d: ", i+1); scanf("%d", &termArray[i].exp); } free = i; A.Finish = free-1;

    printf("\nEnter no of terms in polynomial B: "); scanf("%d", &nos);

    B.Start = free; for (i = B.Start; i < B.Start+nos; i++) { printf("\nEnter coeff. %d: ", i+1-B.Start); scanf("%d", &termArray[i].cf); printf("\nEnter exp. %d: ", i+1-B.Start); scanf("%d", &termArray[i].exp); } free = i; B.Finish = free-1;

    printf("\n%dx^%d", termArray[A.Start].cf, termArray[A.Start].exp); for (i = A.Start + 1; i 0) printf("x^%d", termArray[i].exp); }

    printf("\n%dx^%d", termArray[B.Start].cf, termArray[B.Start].exp); for (i = B.Start + 1; i 0) printf("x^%d", termArray[i].exp); } getch();}

  • DATA STRUCTURES Polynomial Representation#include #define MAXTERM 20/* Data StructurePolynomial representation 1 */struct term { int cf; int exp;};struct poly { int Start, Finish;};

  • DATA STRUCTURES Polynomial Representationstatic int free;static struct term termArray[MAXTERM];main() { int i, j, nos, end; struct poly A, B; free = 0;

  • DATA STRUCTURES Polynomial Representation /* Create polynomials */ printf("\nEnter no of terms in polynomial A: "); scanf("%d", &nos); A.Start = free; for (i = A.Start; i < nos; i++) { printf("\nEnter coeff. %d: ", i+1); scanf("%d", &termArray[i].cf); printf("\nEnter exp. %d: ", i+1); scanf("%d", &termArray[i].exp); } free = i; A.Finish = free-1;

  • DATA STRUCTURES Polynomial Representationprintf("\nEnter no of terms in polynomial B: "); scanf("%d", &nos);

    B.Start = free; for (i = B.Start; i < B.Start+nos; i++) { printf("\nEnter coeff. %d: ", i+1-B.Start); scanf("%d", &termArray[i].cf); printf("\nEnter exp. %d: ", i+1-B.Start); scanf("%d", &termArray[i].exp); } free = i; B.Finish = free-1;

  • DATA STRUCTURES Polynomial Representation

    printf("\n%dx^%d", termArray[A.Start].cf, termArray[A.Start].exp); for (i = A.Start + 1; i 0) printf("x^%d", termArray[i].exp); }

  • DATA STRUCTURES Polynomial Representation printf("\n%dx^%d", termArray[B.Start].cf, termArray[B.Start].exp); for (i = B.Start + 1; i 0) printf("x^%d", termArray[i].exp); } getch();}

  • DATA STRUCTURES Polynomial RepresentationExercise: Extend the above program to add both the polynomials and store the sum at the end. Print the summed polynomial. Tips 1. Compare two terms of each polynomial. If equal, add coefficients and store with proper exponential, then advance to next term for A & B. 2. If A > B, then insert a new term from A and advance to next term of A. If A < B, then insert a new term from B and advance to next term of B. 3. Take care of balance terms at the end of comparison.

  • DATA STRUCTURES Polynomial RepresentationDisadvantages: As we create polynomials, free is continually incremented until it tries to exceed MAXTERM. What happens then? Should we quit?If some polynomial is no longer needed, we may use this space. But, that will require a lot of insertions, change of start and finish pointers. This demands a sophisticated compacting routine coupled with disciplined use of name for polynomials.

  • DATA STRUCTURES Polynomial RepresentationDisadvantages: (contd.)Alternatively, we may use single array of terms creating dynamically using calloc. But this requires the knowledge of the size of the polynomial in advance. Hence, for addition of polynomial, we may have to do to addition twice, once for knowing the size and again for actual addition. This slows down the speed by a factor of 2.

  • DATA STRUCTURES Polynomial Representation

    END of THIS PART

    DATA STRUCTURESPolynomial Representation

  • DATA STRUCTURES Polynomial Representation

  • DATA STRUCTURES Polynomial Representation

  • #include #include main() { int deg, i; float *cf;

    printf("\nEnter degree: "); scanf("%d", &deg);

    cf = (float *) calloc (deg + 1, sizeof(float));

    for (i = 0; i < deg; i++){ printf("\nEnter coeff (%d): ", i); scanf("%f", (cf + i)); } printf("\n"); for (i = 0; i < deg; i++){ if (i > 0) if (*(cf + i) > 0.0) printf("+"); if (*(cf + i) == 0.0); else printf("%2.2fx^%d", *(cf + i), (deg - i)); }}

    (NB. In C notations L = i(i+1)/2+j+1 )???*and in C notations (2n i 1) * i /2 +(j + 1)] ??????? [where, i=row no. & j=coloumn no. & n=order of the given square sparse matrix] n+(n-1)+(n-2)+..till (n-(i-2)) + j-(i-1) [since,the 1st row contains n terms, the second one n-1, and in this way the ith row contains n-(i-1),so the (i-1)th row contains n-(i-2) terms, whereas, in order to locate the desired term in the ith row of the jth coloumn of the given matrix,we need to subtract the terms(zeros-0) from the left-hand side of the diagonal,ie.till (i-1)th coloumn of the ith row, so when we add the jth term in the above summation, it is necessary to subtract (i-1) from it] = n*(i-1) ((i-2)*(i-1))/2 + j-(i-1) = (i-1)*(n-(i-2)/2) - (i-1) + j = (i-1)*(n-((i-2)/2)-1) + j = (i-1)*(2n-i)/2 + j *


Recommended