0% found this document useful (0 votes)
6 views

DS Module 1 - Upto - Sparse Matrix - pptx-1

Uploaded by

keerthi109291
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

DS Module 1 - Upto - Sparse Matrix - pptx-1

Uploaded by

keerthi109291
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 74

Data Structures

3rd SEM,ISE Department, AIT


By,
Ashwini Kamath

1 Data structures ,Module-1 8/30/2024


Course
DATA Objectives AND
STRUCTURES
APPLICATIONS(BCS304)

⚫ Explain the fundamentals of data structures


and their applications.
⚫ Illustrate representation of data structures:
Stack, Queues, Linked Lists, Trees and Graphs.
⚫ To Design and Develop Solutions to problems
using Linear Data Structures
⚫ To discuss applications of Nonlinear Data
Structures in problem solving.
⚫ To introduce advanced Data structure concepts
2
such as Hashing and Optimal Binary Search
Data structures ,Module-1 8/30/2024
Trees
Course Outcomes:
⚫ CO1: Explain different data structures and
their applications.
⚫ CO 2. Apply Arrays, Stacks and Queue data
structures to solve the given problems.
⚫ CO 3. Use the concept of linked list in problem
solving.
⚫ CO 4. Develop solutions using trees and
graphs to model the real-world problem.
⚫ CO 5. Explain the advanced Data Structures
concepts such as Hashing Techniques and
Optimal Binary Search Trees.

3 Data structures ,Module-1 8/30/2024


Content

o Introduction to Data Structures


o Arrays and Structures
o Stacks

o Queues
o Linked Lists

o Linked Lists
o Trees

4 Data structures ,Module-1 8/30/2024


Content
o Trees
o Graphs

o Hashing
o Priority Queues
o Binary Search Trees

5 Data structures ,Module-1 8/30/2024


Textbooks
1. Ellis Horowitz and Sartaj Sahni, Fundamentals of Data
Structures in C, 2nd Ed, Universities Press, 2014.

6 Data structures ,Module-1 8/30/2024


Continuous Internal
Evaluation:
⚫ Two Tests each of 25 Marks (duration 01
hour)
⚫ One assignment for 10 Marks and one
quiz for 15 marks.
⚫ The average of two tests, assignment and
quiz will be out of 50 marks.

Semester End Examination:


Theory SEE will be conducted by University
will be for 50 marks
7 Data structures ,Module-1 8/30/2024
❖Data:Data refers to all the single items that are stored
in a database, either individually or as a set.

❖Information: Information is a set of data which is


processed in a meaningful way according to the given
requirement.

❖Data structure: A data structure is a specialized


format for organizing, processing, retrieving and
storing data.

8 Data structures ,Module-1 8/30/2024


9 Data structures ,Module-1 8/30/2024
Primitive and Non Primitive Data Structure

Primitive Data Structure: The data structure


that are atomic (indivisible) are called primitive.

Examples are integer, real and characters.

Non Primitive Data Structure: The Data


structures that are not atomic are called
non-primitive or composite.

Examples are stacks, queues, array and


string.

10 Data structures ,Module-1 8/30/2024


Non Primitive Data Structure :

▪Compound data structure can be constructed with the


help of any one of the primitive data structure and it
is having a specific functionality. It can be designed
by user.

▪ It can be classified as

1) Linear data structure

2) Non-linear data structure

11 Data structures ,Module-1 8/30/2024


Linear Data Structures :
•A Linear data structure have data elements arranged in
sequential manner and each member element is
connected to its previous and next element

•This connection helps to traverse a linear data structure


in a single level and in single run.
Examples :List, Queue, Stack, Array etc.

Non-linear Data Structures :


•A non-linear data structure has no set sequence of
connecting all its elements and each element can have
multiple paths to connect to other elements.
•Such data structures supports multi-level storage and
often cannot be traversed in single run.
•Such data structures are not easy to implement but are
more efficient in utilizing computer memory.
12•Examples :Tree,
Data structures Graphs etc.
,Module-1 8/30/2024
Linear Data Structures :
Arrays- An array is a collection of items stored at
contiguous memory locations. The idea is to store
multiple items of the same type together.

Stacks- A stack is a list of elements in which items are


inserted and deleted at one end called top of the
stack. The operations are performed in linear
order.This order could be last in first out (LIFO) or
first in Last out (FILO).

13 Data structures ,Module-1 8/30/2024


Queues-A queue can be defined as an ordered list
which enables insert operations to be performed at
one end called REAR and delete operations to be
performed at another end called FRONT.

A queue stores a collection of items similar to a stack;


however, the operation order can only be first in first
out

14 Data structures ,Module-1 8/30/2024


Linked lists- Linked List can be defined as collection
of objects called nodes that are randomly stored in the
memory.

Each element, or node, in a linked list contains a data


item as well as a reference, or link, to the next item in
the list

15 Data structures ,Module-1 8/30/2024


Non-linear Data Structures :

Trees- A tree stores a collection of items in an abstract,


hierarchical way. Each node is linked to other nodes
and can have multiple sub-nodes, also known as
children.

16 Data structures ,Module-1 8/30/2024


Graphs- A graph stores a collection of items in a
non-linear fashion.

▪Graphs are made up of a finite set of nodes, also


known as vertices, and lines that connect them, also
known as edges.

▪ These are useful for representing real-life systems


such as computer networks.

17 Data structures ,Module-1 8/30/2024


Data structure
Operations
The following list of operations applied on linear data
structures
1. Insertion − Add a new data item in the data structure
.
2. Deletion − Delete an existing data item from the
data structure.
3. Traversal − Access each data item exactly once so
that it can be processed.
4. Searching − Find out the location of the data item if
it exists in the data structure
5. 18 Sorting − Arranging
Data structures ,Module-1 the data items in some order.
8/30/2024
Pointers
•The pointer in C language is a variable which stores the address
of another variable.
•The pointer in c language can be declared using * (asterisk
symbol). It is also known as indirection operator used to
dereference a pointer.
•The general form of a pointer variable declaration
type *var-name;
Examples:
int *ip; /* pointer to an integer */
double *dp; /* pointer to a double */
float *fp; /* pointer to a float */
char *ch /* pointer to a character */

19 Data structures ,Module-1 8/30/2024


•example to define a pointer which stores the address of

an integer.

int n = 10;

int* p = &n; // Variable p of type pointer is pointing to the address of t

he variable n of type integer.

•Sometimes pointer can be null. The NULL Pointer can


be used in relational expressions. So to test for the null
pointer in C we can say:

if(pi==NULL)
Or
if(!pi)
20 Data structures ,Module-1 8/30/2024
An example of using pointers to print the address and value is given
below.

#include<stdio.h>
int main(){
int number=50;
int *p;
p=&number; //stores the address of number variable
printf("Address stored in p variable is %x \n",p);
// p contains the address of the number therefore printing p gives the ad
dress of number.
printf("Address of var variable: %x\n", &number);
printf("Value of p variable is %d \n",*p); // As we know that * is used to derefe
rence a pointer, //so if
we print *p, we will get the value stored at the address contained by p.
return 0;
21} Data structures ,Module-1 8/30/2024
Pointers Can Be Dangerous
Because pointers provide access to a memory location and
because data and executable code exist in memory together,
misuses of pointers can lead to very subtle errors.

Potential Problems with Pointers


uninitialized pointers,
dangling pointer

Uninitialized pointers
Uninitialized pointer pose a significant threat.
•the value stored in an uninitialized pointer could be
randomly pointing anywhere in memory.
•Storing a value using an uninitialized pointer has the
potential to overwrite anything in your program, including
your program itself

Dangling Pointers
Dangling pointers refer to a pointer which was pointing at an
object
22 that has been
Data structures deleted.
,Module-1 8/30/2024
Dynamic Memory
Allocationthe size of the array you declared may be
•Sometimes

insufficient.

• To solve this issue, you can allocate memory manually

during run-time. This is known as Dynamic memory

allocation

•To allocate memory dynamically, we can use

functions

1. malloc(),
Data structures ,Module-1
2.
23
calloc(), 8/30/2024
mallo
•The name "malloc" stands for memory allocation.
c()
•The malloc() function reserves a block of memory of the specified number of
bytes. And, it returns a pointer of void which can be casted into pointers of any form.

Syntax of malloc()
ptr = (castType*) malloc(size);

Example
ptr = (float*) malloc(100 * sizeof(float));

The above statement allocates 400 bytes of memory. It's because the size
of float is 4 bytes. And, the pointer ptr holds the address of the first byte in
the allocated memory.
•The expression results in a NULL pointer if the memory cannot be
allocated.
Data structures ,Module-1 8/30/2024
24
##Program to demonstrate malloc and free
#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,*pi;
float f,*pf;
pi=(int*)malloc(sizeof(int));
pf=(float*)malloc(sizeof(float));
*pi=1024;
*pf=3.14;
printf("an integer=%d, a float=%f \n",*pi,*pf);
free(pi);
free(pf);
25 } Data structures ,Module-1 8/30/2024
Sometimes malloc may fail for lack of sufficient memory,so
that we can check pointer is null.

if((pi= (int*)malloc(sizeof(int)))==NULL||(
pf=(float*)malloc(sizeof(float)))==NULL)
{
fprintf(stderr,”Insufficient memory”);
Exit(EXIT_FAILURE);
}

Or

if(!(pi= (int*)malloc(sizeof(int)))||!(
pf=(float*)malloc(sizeof(float))))
{
fprintf(stderr,”Insufficient memory”);
Exit(EXIT_FAILURE);
}
26 Data structures ,Module-1 8/30/2024
MACRO function for checking NULL pointer

#define MALLOC(p,s) \
if(!((p)=malloc(s))) { \
fprintf(stderr,”Insufficient memory”);\
Exit(EXIT_FAILURE);\
}

Now the two lines that invoke malloc may be replaced by the code

MALLOC(pi,sizeof(int));
MALLOC(pf,sizeof(float));
27 Data structures ,Module-1 8/30/2024
free()
Dynamically allocated memory created with calloc() or malloc() doesn't get
freed on their own. You must explicitly use free() to release the space.

Syntax of free()
free(ptr);

This statement frees the space allocated in the memory pointed by ptr.

28 Data structures ,Module-1 8/30/2024


•The name "calloc" stands for contiguous allocation.

•The malloc() function allocates memory and leaves the memory


uninitialized. Whereas, the calloc() function allocates memory and
initializes all bits to zero.

Syntax of calloc()

ptr = (castType*)calloc(n, size);

Example:
ptr = (float*) calloc(25, sizeof(float));
The above statement allocates contiguous space in memory for 25
elements of type float.

int *x;
x=calloc(n,sizof(int));

29 Data structures ,Module-1 8/30/2024


Array as Abstract Dataype

30 Data structures ,Module-1 8/30/2024


ARRAYS
⚫ An Array is defined as, an ordered set of similar
data items. All the data items of an array are
stored in consecutive memory locations.
⚫ The data items of an array are of same type and
each data items can be accessed using the same
name but different index value.
⚫ An array is a set of pairs, , such that each index
has a value associated with it.
⚫ It can be called as corresponding or a mapping
⚫ Ex: <index,values>
⚫ < 0 , 25 > list[0]=25
⚫ < 1 , 15 > list[1]=15
⚫ < 2 , 20 > list[2]=20
Data structures ,Module-1

31
< 3 , 17 > list[3]=17 8/30/2024
Array in C Declaration:
⚫ A one dimensional array in C is declared by
adding brackets to the name of a variable.
⚫ Ex: int list[5], *plist[5];

⚫ The array list[5], defines 5 integers and in C


array start at index 0, so list[0], list[1], list[2],
list[3], list[4] are the names of five array
elements which contains an integer value.

⚫ The array *plist[5], defines an array of 5


pointers to integers. Where, plist[0], plist[1],
32 plist[2], plist[3],
Data structures ,Module-1 plist[4] are the five 8/30/2024
array
Implementation:
⚫ When the complier encounters an array
declaration, list[5], it allocates five
consecutive memory locations. Each
memory is large enough to hold a single
integer.
⚫ The address of first element of an array is
called Base Address. Ex: For list[5] the
address of list[0] is called the base address.
⚫ If the memory address of list[i] need to
compute by the compiler, then the size of
the int would get by sizeof (int), then
memory address of list[i] is as follows:
⚫ list[i] = α + i * sizeof (int)
33 Data structures ,Module-1 8/30/2024
⚫ Where, α is base address
34 Data structures ,Module-1 8/30/2024
Dynamically allocated Arrays

One Dimensional Arrays


int a[20];

•If the user wishes allocate more numbers, again user has to
change the size of the array and recompile it.
•So to avoid this, During runtime allocate memory for the array.

Example:
int i,n,*list;
printf(“Enter the number of numbers to generate:”);
scanf(“%d”,&n);
if(n<1)
{
fprintf(stderr,”Improper value of n\n”);
Exit(EXIT_FAILURE);
}
MALLOC(list,n*sizeof(int));
35 Data structures ,Module-1 8/30/2024
Multidimensional
Arrays
•C programming language allows multidimensional arrays.

• Here is the general form of a multidimensional array


declaration −

type name[size1][size2]...[sizeN];

For example, the following declaration creates a three


dimensional integer array
4
column
int Array[5][10][4]; // 5 2-dimensional array with 10 rows and
Array 1
4 columns s Array 2
Array 3
Array 4
10
Array 5
rows

36 Data structures ,Module-1 8/30/2024


Two-dimensional Arrays
•The simplest form of multidimensional array is the
two-dimensional array.
• A two-dimensional array is, in essence, a list of one-dimensional
arrays.
•To declare a two-dimensional integer array of size [x][y], you would
write something as follows −

type arrayName [ x ][ y ];

•Where type can be any valid C data type and arrayName will be a
valid C identifier.

• A two-dimensional array can be considered as a table which will


have
37 xData structures ,Module-1
number of rows and y number of columns 8/30/2024
•Array of array representation to represent a
multidimensional array.
•A two dimension array is represented as a
one-dimensional array in which each element is,
itself ,a one dimensional array.

Ex:int x[3][5];

•Create one-dimensional array x whose length is 3


•Each element of x is a one dimensional array whose
length is 5.
FollowingX[0] fig shows
[0] structure
[1] [2] [3] [4]
x[1]
X[2]

38 Data structures ,Module-1 8/30/2024


Pointer to Pointer:
▪A pointer to a pointer is a form of multiple indirection, or a
chain of pointers. Normally, a pointer contains the address of
a variable.
▪ When we define a pointer to a pointer, the first pointer
contains the address of the second pointer, which points to
the location that contains the actual value as shown below.

•A variable that is a pointer to a pointer must be declared as


such. This is done by placing an additional asterisk in front of
its name.
•For example, the following declaration declares a pointer to a
39 Data structures ,Module-1 8/30/2024
pointer of type int −
•C finds the element x[i][ j] by first accessing the pointer
in x[i]
•This pointer gives us address, in memory, of the
zeroeth element of row i of the array
•Then by adding j*sizeof(int) to this pointer, the address
of the jth element of row i

• consider an example

int **myArray; /* allocates memory for a 3


myArray=make2dArray(3,5);by 5 two-dimensional array
of integers */
myArray[1][2]=6;

40 Data structures ,Module-1 8/30/2024


int **make2darray(int rows,int cols)
{
int **x, i; /*get memory for row pointers*/
MALLOC(x,rows*sizeof(*x)); /* get memory for each
row ,this is =to int *,gets the address of the
row */
for(i=0;i<rows;i++)
MALLOC(x[i],cols*sizeof(**x)); /* to int ,gets the
value at the particular position*/

return x;
}

41 Data structures ,Module-1 8/30/2024


The C library function void *realloc(void *ptr, size_t
size) attempts to resize the memory block pointed to
by ptr that was previously allocated with a call
to malloc or calloc.
Declaration
void *realloc(void *ptr, size_t size)Parameters
•ptr − This is the pointer to a memory block previously
allocated with malloc, calloc or realloc to be reallocated. If this
is NULL, a new block is allocated and a pointer to it is
returned by the function.
•size − This is the new size for the memory block, in bytes. If it
is 0 and ptr points to an existing block of memory, the
memory block pointed by ptr is deallocated and a NULL
pointer is returned.
42 Data structures ,Module-1 8/30/2024
•This function returns a pointer to the newly allocated
Structures and Unions

43 Data structures ,Module-1 8/30/2024


Defining a Structure

•Structure (struct) is a collection of data items, where


each item is identified as to its type and name
•To define a structure, you must use the struct
statement.
• The struct statement defines a new data type, with
more than one member. The format of the struct
statement is as follows − Example:
struct Person
{
struct structureName char name[50];
{ int age;
dataType member1; float salary;
dataType member2; };
...
}; Data structures ,Module-1
44 8/30/2024
Create struct
variables
•When a struct type is declared, no storage or memory is
allocated.
•To allocate memory of a given structure type and work with it,
we need to create variables.
Another way of creating a
•struct Person
struct variable is:
{ struct Person
char name[50]; {
int age;
float salary; char name[50];
}; int age;
float salary;
int main() } person1, person2, p[20];
{
struct Person
person1,
person2, p[20];
return 0;
45 Data structures ,Module-1 8/30/2024
}
Access members of a
structure

There are two types of operators used for accessing members of a


structure.

.(dot) - Member operator


🡪(arrow) - Structure pointer operator
. (dot)- Member operator
•To access any member of a structure, we use the member access
operator (.).
•The member access operator is coded as a period between the
structure variable name and the structure member that we wish to
access.
•use
46
the keyword
Data struct to define variables of structure type.
structures ,Module-1 8/30/2024
Store Information and Display it Using Structure

#include <stdio.h>
struct student {
char name[50];
int roll;
float marks;
} s;

int main()
{
printf("Enter information:\n");
printf("Enter name: ");
scanf("%s", s.name);
printf("Enter roll number: ");
scanf("%d", &s.roll);
printf("Enter marks: ");
scanf("%f", &s.marks);

47 Data structures ,Module-1 8/30/2024


printf("Displaying Information:\n");
printf("Name: ");
printf("%s", s.name);
printf("Roll number: %d\n", s.roll);
printf("Marks: %.1f \n", s.marks);
return 0;
}

Output
Enter information:
Enter name: Ram
Enter roll number: 23
Enter marks: 34.5
Displaying Information:
Name: Ram
Roll number: 23
Marks: 34.5

48 Data structures ,Module-1 8/30/2024


Nested Structure

•A structure can be nested inside another structure.

•In other words, the members of a structure can be of any other


type including structure.

49 Data structures ,Module-1 8/30/2024


#include<stdio.h>
struct address
{
char city[20];
int pin;
char phone[14];
};
struct employee
{
char name[20];
struct address add;
};
void main ()
{
struct employee emp;
printf("Enter employee information?\n");
scanf("%s %s %d %s",emp.name,emp.add.city, &emp.add.pin, emp.a
dd.phone);
printf("Printing the employee information....\n");
printf("name: %s\nCity: %s\nPincode: %d\nPhone: %s",emp.name,e
mp.add.city,
emp.add.pin,emp.add.phone);
50 } Data structures ,Module-1 8/30/2024
Self Referential Structures

•Self Referential structures are those structures that have one or


more of its components is a pointer to itself .

•Self Referential structures usually require dynamic storage


management routines to explicitly obtain and release memory.

51 Data structures ,Module-1 8/30/2024


Example:
typedef struct
{
char data;
struct list *link;
} list;

list item1,item2,item3;
item1.data=’a’;
item2.data=’b’;
item3.data=’c’;

item1.link=item2.link=item3.link=NULL;

•Structures item1,item2 and item3 each contain the data item a,b
& c respectively, and the NULL pointer.

52 Data structures ,Module-1 8/30/2024


•These structures together by replacing the null link
field in item2 with one that points to item3 and by
replacing the null link field in item1 with one that
points to item2.

Item1.link=&item2;
Item2.link=&item3

53 Data structures ,Module-1 8/30/2024


Unions
⚫ A union declaration is similar to a
structure, but the fields of a union must
share their memory space. This means that
only
typedef oneGender
struct field of the union is "active" at any
typedef struct Person
{ given time. {
enum tag-field {female, char name[50];
male} gender; int age;
union float salary;
{ date dob;
int children; Gender g;
int beard ; };
} u; Person p1, p2;
};
54 Data structures ,Module-1 8/30/2024
THE POLYNOMIAL

•A polynomial is an expression representing a sum of many terms.

,where each term has form axe, where x is the variable, a is the

coefficient and e is the exponent


•. The largest exponent is the polynomial’s degree.

55 Data structures ,Module-1 8/30/2024


Two such polynomials are
A(x) = 3x² + 2x + 4 and B(x) =x4 + 10x³ + 3x² + 1
▪The largest (or leading) exponent of a polynomial is called its
degree. Coefficients that are zero are not displayed.
▪The term with exponent equal to zero does not show the
variable. since x raised to a power of zero is I.
▪ Assume that we have two polynomials, A (x) = Σ ai xi and B(x)= Σ

bi xi Then

▪A(x)+B(x)= Σ (ai+bi)xi
▪A(x).B(x)= Σ (aixi . Σ(bjxj))

▪. Similarly. we can define subtraction and division on


polynomials.
56 Data structures ,Module-1 8/30/2024
Polynomial Addition
•The algorithm works by comparing terms from the two polynomials until
one or both of the polynomials becomes empty.

•The switch statement performs the comparisons and adds the proper term
to the new polynomial d.

•, if one polynomial becomes empty, we copy the remaining terms from the
from the non empty polynomial into d.

57 Data structures ,Module-1 8/30/2024


Polynomial Addition
•If the polynomial is sparse , that is ,the number of terms with nonzero
coefficient is small relative to the degree of the polynomial.

•To preserve space the alternative representation that uses only one global
array,terms,to store all our polynomials .

C Declaration is

MAX_TERMS 100 /* size of terms array*/


typedef struct {
float coef;
int expon;
}polynomial;
polynomial terms[MAX_TERMS];

int58avail=0;
Data structures ,Module-1 8/30/2024
Array Representation
•Consider the two polynomials A(x) =2 x 1000 + 1 and B(x) = X4 + 10x³ + 3x² + 1.
• These could be stored in the array termArray as shown-in Figure.

•StartA and StartB give the location of the first term of A and B respectively,
whereas FinishA and FinishB give the location of the last term of A and B.
•The static class member avail gives the location of the next free location in the
array termArray.
•Here, StartA = 0, Finish A= 1, StartB = 2, FinishB = 5, and avail = 6.
59 Data structures ,Module-1 8/30/2024
A(x) =2 x 1000 + 1

B(x)=X4 + 10x³ + 3x² +


1

StartA = 0,
Finish A= 1,
StartB = 2,
FinishB = 5

60 Data structures ,Module-1 8/30/2024


avail = 6

61 Data structures ,Module-1 8/30/2024


Sparse Matrix
•A matrix contains m rows and n columns of elements as
illustrated in below figures. In this figure, the elements are
numbers.
•The first matrix has four rows and three columns and the
second has six rows and six columns. We write m x n (read "m
by n") to designate a matrix with m rows and n columns.
•The total number of elements in such a matrix is mn. If m
equals n, the matrix is square

62 Data structures ,Module-1 8/30/2024


•A matrix which contains many zero entries or very
few non-zero entries is called as Sparse matrix. In the
figure B contains only 8 of 36 elements are nonzero
and that is sparse.
•A sparse matrix can be represented in 1-Dimension, 2-
Dimension and 3- Dimensional array. When a sparse
matrix is represented as a two-dimensional array as
shown in Figure B, more space is wasted.
Example: consider the space requirements necessary
to store a 1000 x 1000 matrix that has only 2000
non-zero
63 elements.
Data structures ,Module-1 The corresponding
8/30/2024
•Sparse Matrix Representation
• An element within a matrix can characterize by
using the triple This means that, an array of triples
is used to represent a sparse matrix.
• Organize the triples so that the row indices are in
ascending order.
•so we must know the number of rows and
columns, and the number of nonzero elements in
the matrix

64 Data structures ,Module-1 8/30/2024


65 Data structures ,Module-1 8/30/2024
Sparse Matrix Representation

Sparse matrix Declaration


#define MAX_TERMS 101 /* maximum number of
terms +1*/
typedef struct
{
int col;
int row;
int value;
} term;
term a[MAX_TERMS];

66 Data structures ,Module-1 8/30/2024


•The below figure shows the representation of matrix in the array
“a”
• a[0].row contains the number of rows,
• a[0].col contains the number of columns and
•a[0].value contains the total number of nonzero entries.
•Positions 1 through 8 store the triples representing the nonzero
entries.
row col
• The row index is in the field row, the column
valueindex is in the field
col, and the value is in the field value. The triples are ordered by
row and within rows by columns.

67 Data structures ,Module-1 8/30/2024


Transposing a Matrix

•To transpose a matrix, interchange the rows and columns.


•This means that each element a[i][ j] in the original matrix
becomes element a[ j][i] in the transpose matrix.
A good algorithm for transposing a matrix:
-------------------------------------------------------------------
Example

for each row i


take element <i.j,value>and store it
as element <j,i,value> of the transpose;
-----------------------------------------------------------------------
• If we process the original matrix by the row indices it is difficult to
know exactly where to place element in the transpose matrix until
we processed all the elements that precede it.
•This can be avoided by using the column indices to determine the
placement of elements in the transpose matrix. This suggests the
following algorithm:
-----------------------------------------------------------------
Data structures ,Module-1 8/30/2024
for all
68 elements in column j
Transpose matrix

69 Data structures ,Module-1 8/30/2024


70 Data structures ,Module-1 8/30/2024
REPRESENTATION OF
MULTIDIMENSIONAL ARRAYS
⚫ The internal representation of
multidimensional arrays requires more
complex addressing formulas. If an array is
declared a [upper0][upper1J • • • [uppern], then
it is easy to see that the number of elements in
the array is:

⚫ where H is the product of the upperi's. For


instance, if we declare a as a [10][ 10][ 10], then
71 we require
Data 10 .10 . 10 = 1000 units of storage 8/30/2024
structures ,Module-1 to
hold the array.
⚫ Representing array using row major order stores
multidimensional arrays by rows. For instance,
we interpret the two-dimensional array A
[upper0][upper1 ] as upper0 rows, row0, row1, • • • ,
rowupper0-1, each row containing upper1
elements.

⚫ If we assume that α is the address of A [0][0], then


the address of A [i ][0] is α + i • upper1 because there
are i rows, each of size upper1, preceding the first
element in the ith row. The address of an arbitrary
element, a [i][j], is α + i • upper1 + j.

72 Data structures ,Module-1 8/30/2024


73 Data structures ,Module-1 8/30/2024
Thank
you

74 Data structures ,Module-1 8/30/2024

You might also like