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

DSA Module 1

DATA FOR LIFE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views

DSA Module 1

DATA FOR LIFE
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 34

DATA STRUCTURES AND APPLICATIONS

MODULE-I

Introduction to Data Structures


Data Structure is a way of collecting and organizing data in such a way that we can perform operations
on these data in an effective way. Data Structures is about rendering data elements in terms of some
relationship, for better organization and storage. For example, we have data player's name "Virat"
and age 26. Here "Virat" is of String data type and 26 is of integer data type.
We can organize this data as a record like Player record. Now we can collect and store player's
records in a file or database as a data structure. For example: "Dhoni" 30, "Gambhir" 31, "Sehwag"
33.
➢ In simple language, Data Structures are structures programmed to store ordered data, so that
various operations can be performed on it easily.
➢ It represents the knowledge of data to be organized in memory. It should be designed and
implemented in such a way that it reduces the complexity and increases the efficiency.
➢ Data may be organized in many different ways. The logical or mathematical model of a
particular organization of data is called a data structure.

Classification of data structures (Primitive & Non Primitive)


As we have discussed above, anything that can store data can be called as a data structure.

Data structures are generally categorized into two classes:


➢ Primitive data Structures
➢ Non-primitive data Structures
Primitive Data Structures
Primitive data structures are the fundamental data types which are supported by a programming
language. Some basic data types are integer, real, character, and Boolean. The terms ‘data type’,
‘basic data type’, and ‘primitive data type’ are often used interchangeably.
Non-Primitive Data Structures
Non-primitive data structures are those data structures which are created using primitive data
structures. Examples of such data structures include linked lists, stacks, trees, and graphs.

Based on the structure and arrangement of data, non-primitive data structures is further classified into
➢ Linear Data Structure
Page 1
DATA STRUCTURES AND APPLICATIONS
➢ Non-linear Data Structure
Linear data Structures
If the elements of a data structure are stored in a linear or sequential order, then it is a linear data
structure. Examples include arrays, linked lists, stacks, and queues.
Linear data structures can be represented in memory in two different ways.
➢ One way is to have to a linear relationship between elements by means of sequential memory
locations.
➢ The other way is to have a linear relationship between elements by means of links.
Non-linear data Structures
If the elements of a data structure are not stored in a sequential order, then it is a non-linear data
structure.
➢ The relationship of adjacency is not maintained between elements of a non-linear data
structure.
➢ This structure is mainly used to represent data containing a hierarchical relationship between
elements.
Examples include trees and graphs.

Figure (a). Classifications of Data Structures

Data structure Operations


Data are processed by means of certain operations which appearing in the data structure. In fact
particular data structure that one chooses for a given situation depends largely on the frequency with

Page 2
DATA STRUCTURES AND APPLICATIONS
which specific operations are performed. This section introduces the reader to some of the most
frequently used of these operations.
(1) Traversing: Accessing each record exactly once so that certain items in the record may be
processed (This accessing and processing is sometimes called visiting the record).
(2) Searching: Finding the location of the record with a given key value, or finding the location of
all records which satisfy one or more conditions.
(3) Inserting: Adding a new record to the structure.
(4) Deleting: Removing the record from the structure.
(5) Sorting: Arranging the data or record in some logical order (Ascending or descending order).
(6) Merging: Combining the record in two different sorted files into a single sorted file.
Review of Arrays
An array data structure, or simply an array, is a data structure consisting of a collection of
(mainly of similar data types) elements (values or variables), each identified by at least
one array index or key. An array is stored so that the position of each element can be computed
from its index tuple by a mathematical formula.
ARRAYS IN C
➢ A one-dimensional array can be declared as follows:
int list[5]; //array of 5 integers
int *plist[5]; //array of 5 pointers to integers

➢ Compiler allocates 5 consecutive memory-locations for each of the variables 'list' and 'plist'.
➢ Address of first element list [0] is called base-address.
➢ Memory-address of list[i] can be computed by compiler as

α + i * sizeof (int) where α =base address

Page 3
DATA STRUCTURES AND APPLICATIONS

Program to find sum of n numbers using array


#define MAX_SIZE 100
float sum(float [ ], int);

float input[MAX_SIZE], answer;


int i;

main ( )
{

for (i = 0; i < MAX_SIZE; i++)


input[i] = i;
answer = sum(input, MAX_SIZE);
printf("The sum is: %f\n", answer);

float sum(float list[ ], int n)

{
int i;

float tempsum = 0;
for (i = 0; i < n; i++)

tempsum += list[i];
return tempsum;
}

Program to print both address of ith element of given array & the value found at that address.

void print1(int *ptr, int rows)


{

/* print out a one-dimensional array using a pointer */


int i;

printf(“Address Contents\n”);
for (i=0; i < rows; i++)
Page 4
DATA STRUCTURES AND APPLICATIONS

printf(“%8u%5d\n”, ptr+i, *(ptr+i));


printf(“\n”);

void main()
{

int one[ ] = {0, 1, 2, 3, 4};


print1(&one[0], 5);

Output

Arrays are generally used when we want to store large amount of similar type of data. But they have
the following limitations:
➢ Arrays are of fixed size.
➢ Data elements are stored in contiguous memory locations which may not be always available.
➢ Insertion and deletion of elements can be problematic because of shifting of elements from
their positions.

STRUCTURES

In C,a way to group data that permits the data to vary in type. This mechanism is called the structure,
for short struct.
A structure (a record) is a collection of data items, where each item is identified as to its type and
name.
Syntax:
struct
{
data_type member 1;
data_type member 2;
………………………

Page 5
DATA STRUCTURES AND APPLICATIONS
………………………
data_type member n;
} variable_name;

Ex: struct {
char name[10];
int age;
float salary;
} Person;

The above example creates a structure and variable name is Person and that has three fields:
name = a name that is a character array
age = an integer value representing the age of the person
salary = a float value representing the salary of the individual
Assign values to fields
To assign values to the fields, use . (dot) as the structure member operator. This operator is used to
select a particular member of the structure
Ex: strcpy(Person.name,“james”);
Person.age = 10;
Person.salary = 35000;
Type-Defined Structure
The structure definition associated with keyword typedef is called Type-Defined Structure.
Syntax 1:
typedef struct
{
data_type member 1;
data_type member 2;
………………………
………………………
data_type member n;
}Type_name;
Where,
Page 6
DATA STRUCTURES AND APPLICATIONS
➢ typedef is the keyword used at the beginning of the definition and by using typedef user
defined data type can be obtained.

➢ struct is the keyword which tells structure is defined to the complier

➢ The members are declare with their data_type

➢ Type_name is not a variable, it is user defined data_type.


Syntax 2:
struct struct_name
{
data_type member 1;
data_type member 2;
………………………
………………………
data_type member n;
};
typedef struct struct_name Type_name;

Ex:
typedef struct
{
char name[10];
int age;
float salary;
}humanBeing;

In above example, humanBeing is the name of the type and it is a user defined data type.
Declarations of structure variables:
humanBeing person1, person2;
This statement declares the variable person1 and person2 are of type humanBeing.
Structure Operation
The various operations can be performed on structures and structure members.

Page 7
DATA STRUCTURES AND APPLICATIONS
1. Structure Equality Check:
Here, the equality or inequality check of two structure variable of same type or dissimilar type is not
allowed
typedef struct
{
char name[10];
int age;
float salary;
}humanBeing;
humanBeing person1, person2;
if (person1 = = person2) is invalid.
While structures cannot be directly checked for equality or inequality, we can write a function to do
this.
The valid function is shown below:
#define FALSE 0
#define TRUE 1
//A typical function call might be:
if (humansEqual(person1,person2))
printf("The two human beings are the same\n");
else
printf("The two human beings are not the same\n");
//Function to check equality of structures
int humansEqual(humanBeing person1, humanBeing person2)
{
/* return TRUE if person1 and person2 are the same human being otherwise
return FALSE */
if (strcmp(person1.name, person2.name))
return FALSE;
if (person1.age != person2.age)
return FALSE;
if (person1.salary != person2.salary)
return FALSE;
Page 8
DATA STRUCTURES AND APPLICATIONS
return TRUE;
}
2. Assignment operation on Structure variables:
person1 = person2
The above statement means that the value of every field of the structure of person 2 is assigned as the
value of the corresponding field of person 1, but this is invalid statement.
Valid Statements is given below:
strcpy(person1.name, person2.name);
person1.age = person2.age;
person1.salary = person2.salary;
Structure within a structure:
There is possibility to embed a structure within a structure. There are 2 ways to embed structure.
1. The structures are defined separately and a variable of structure type is declared inside the
definition of another structure. The accessing of the variable of a structure type that are nested inside
another structure in the same way as accessing other member of that structure
Example: The following example shows two structures, where both the structure are defined
separately.
typedef struct
{
int month;
int day;
int year;
}date;
typedef struct
{
char name[10];
int age;
float salary;
date dob;
} humanBeing;
humanBeing person1;
A person born on February 11, 1944, would have the values for the date struct set as:
Page 9
DATA STRUCTURES AND APPLICATIONS
person1.dob.month = 2;
person1.dob.day = 11;
person1.dob.year = 1944;
2. The complete definition of a structure is placed inside the definition of another structure.
Example:
typedef struct
{
char name[10];
int age;
float salary;
struct
{ int month;
int day;
int year;
} date;
} humanBeing;
SELF-REFERENTIAL STRUCTURES
➢ A self-referential structure is one in which one or more of its components is a pointer to itself.
➢ These require dynamic storage management routines (malloc & free) to explicitly obtain and
release memory.
typedef struct
{
char data;
struct list *link; //list is a pointer to a list structure
}list;
➢ Consider three structures and values assigned to their respective fields:
list item1,item2,item3;
item1.data='a';
item2.data='b';
item3.data='c';
item1.link=item2.link=item3.link=NULL;

Page 10
DATA STRUCTURES AND APPLICATIONS
➢ We can attach these structures together as follows
item1.link=&item2;
tem2.link=&item3;

INTERNAL IMPLEMENTATION OF STRUCTURES


➢ The size of an object of a struct or union type is the amount of storage necessary to represent
the largest component, including any padding that may be required.
➢ Structures must begin and end on the same type of memory boundary. For ex, an even byte
boundary (2, 4, 6 or 8).

Union
A union is a special data type available in C that allows us to store different data types in the same
memory location. You can define a union with many members, but only one member can contain a
value at any given time. Unions provide an efficient way of using the same memory location for
multiple-purpose.
#include <stdio.h>
#include <string.h>
union Data
{
int i;
float f;
char str[20];
};
int main( )
{
union Data data;
printf( "Memory size occupied by data : %d\n", sizeof(data));
return 0;
}

Page 11
DATA STRUCTURES AND APPLICATIONS
The memory occupied by a union will be large enough to hold the largest member of the union. For
example, in the above example, Data type will occupy 20 bytes of memory space because this is the
maximum space which can be occupied by a character string.
POINTERS

➢ In computer science, a pointer is a programming language data type whose value refers
directly to (or "points to") another value stored elsewhere in the computer memory using its
address.
➢ This is a memory-location which holds the address of another memory-location.
➢ The 2 most important operators used w.r.t pointer are:
& (address operator)
* (dereferencing/indirection operator)
#include<stdio.h>
void main()
{
int a=10,b=20; //Declare a data variable
int *p,*q; //Declare a pointer variable
int p=&a, q=&b; //Initialize a pointer variable
int x=*p + *q;
printf("%d+%d=%d",*p,*q, x); //Access data using pointer variable
}

NULL POINTER
➢ The null pointer points to no object or function.
i.e. it does not point to any part of the memory.

if(p==NULL)
printf("p does not point to any memory");
else
printf("access the value of p");

DYNAMIC MEMORY ALLOCATION


➢ This is process of allocating memory-space during execution-time (or run-time).
➢ This is used if there is an unpredictable storage requirement.
➢ Memory-allocation is done on a heap.
➢ Memory management functions include:
▪ malloc (memory allocate)
▪ calloc (contiguous memory allocate)

Page 12
DATA STRUCTURES AND APPLICATIONS
▪ realloc (resize memory)
▪ free (de-allocate memory)
➢ malloc function is used to allocate required amount of memory-space during run-time.
➢ If memory allocation succeeds, then address of first byte of allocated space is returned. If
memory allocation fails, then NULL is returned.
#include<stdio.h>
void main()
{
int i,*pi;
pi=(int*)malloc(sizeof(int));
*pi=1024;
printf("an integer =%d",pi);
free(pi);
}
➢ If we frequently allocate the memory space, then it is better to define a macro as shown below:

#define MALLOC(p,s) \
if(!((p)==malloc(s))) \
{ \
printf("insufficient memory"); \
exit(0); \
}

➢ Now memory can be initialized using following:


MALLOC(pi,sizeof(int));

MALLOC(pf,sizeof(float));

DANGLING REFERENCE

➢ Whenever all pointers to a dynamically allocated area of storage are lost, the storage is lost
to the program. This is called a dangling reference.

POINTERS CAN BE DANGEROUS

1) Set all pointers to NULL when they are not actually pointing to an object. This makes sure that
you will not attempt to access an area of memory that is either
→ out of range of your program or
Page 13
DATA STRUCTURES AND APPLICATIONS
→ that does not contain a pointer reference to a legitimate object .

2) Use explicit type casts when converting between pointer types.

pi=malloc(sizeof(int)); //assign to pi a pointer to int

pf=(float*)pi; //casts an ‘int’ pointer to a ‘float’ pointer

3) Pointers have same size as data type 'int'. Since int is the default type specifier, some
programmers omit return type when defining a function. The return type defaults to ‘int’ which
can later be interpreted as a pointer. Therefore, programmer has to define explicit return types
for functions.
Swap function using pointers:
void swap(int *p, int *q) //both parameters are pointers to ints
{
int temp=*p; //declares temp as an int and assigns to it the contents of what p points to
*p=*q; //stores what q points to into the location where p points
*q=temp; //places the contents temp in location pointed to by q

Representation of Linear Arrays in Memory


The elements of linear array are stored in consecutive memory locations

Page 14
DATA STRUCTURES AND APPLICATIONS

DYNAMICALLY ALLOCATED ARRAYS


ONE-DIMENSIONAL ARRAYS
• When writing programs, sometimes we cannot reliably determine how large an array must be.
• A good solution to this problem is to
➢ defer this decision to run-time &
➢ Allocate the array when we have a good estimate of required array-size.
Page 15
DATA STRUCTURES AND APPLICATIONS

Dynamic memory allocation can be performed as follows:


int i,n,*list;
printf("enter the number of numbers to generate");
scanf("%d",&n);
if(n<1)
{
printf("improper value");
exit(0);
}
MALLOC(list, n*sizeof(int));

• The above code would allocate an array of exactly the required size and hence would not result in
any wastage.

TWO DIMENSIONAL ARRAYS

• These are created by using the concept of array of arrays.


• A 2-dimensional array is represented as a 1-dimensional array in which each element has a pointer
to a 1-dimensional array as shown below
int x[5][7]; //we create a 1-dimensional array x whose length is 5;
//each element of x is a 1-dimensional array whose length is 7.

• Address of x[i][j] = x[i]+j*sizeof(int)

Array-of-arrays representation

Dynamically create a two-dimensional array

Int ** make2darry(int rows, int cols)


{
Int **x,i;
Page 16
DATA STRUCTURES AND APPLICATIONS
/* get memory for new pointer*/
MALLOC( x, rows * sizeof (*x));

/* get memory for each row*/


for( i=0; i<rows; i++)
MALLOC( x[i], cols*sizeof (**x));
return x;
}
CALLOC
• These functions
→ allocate user-specified amount of memory &
→ Initialize the allocated memory to 0.
• On successful memory-allocation, it returns a pointer to the start of the new block.
On failure, it returns the value NULL.
• Memory can be allocated using calloc as shown below:

int *p;
p=calloc(n, sizeof(int)); //where n=array size

• To create clean and readable programs, a CALLOC macro can be created as shown below:

#define CALLOC(p,n,s) \
if((p=calloc(n,s))==NULL) \
{ \
printf("insufficient memory"); \
exit(0); \
}

REALLOC

• These functions resize memory previously allocated by either malloc or calloc.


For example,
realloc(p,s); //this changes the size of memory-block pointed at by p to s.
• When s>oldSize, the additional s-oldSize have an unspecified value and
when s<oldSize, the rightmost oldSize-s bytes of old block are freed.
• On successful resizing, it returns a pointer to the start of the new block. On failure, it returns the
value NULL.
• To create clean and readable programs, the REALLOC macro can be created as shown below

#define REALLOC(p,s) \
if((p=realloc(p,s))==NULL) \
{ \
printf("insufficient memory"); \
exit(0); \
}
Page 17
DATA STRUCTURES AND APPLICATIONS

ARRAY OPERATIONS
1. Traversing
➢ Let A be a collection of data elements stored in the memory of the computer. Suppose if the
contents of the each elements of array A needs to be printed or to count the numbers of
elements of A with a given property can be accomplished by Traversing.
➢ Traversing is a accessing and processing each element in the array exactly once.
Algorithm 1: (Traversing a Linear Array)
Hear LA is a linear array with the lower bound LB and upper bound UB. This algorithm traverses
LA applying an operation PROCESS to each element of LA using while loop.
1. [Initialize Counter] set K:= LB

2. Repeat step 3 and 4 while K ≤ UB

3. [Visit element] Apply PROCESS to LA [K]

4. [Increase counter] Set K:= K + 1


[End of step 2 loop]
5. Exit

Algorithm 2: (Traversing a Linear Array)


Hear LA is a linear array with the lower bound LB and upper bound UB. This algorithm traverses
LA applying an operation PROCESS to each element of LA using repeat – for loop.
1. Repeat for K = LB to UB
Apply PROCESS to LA [K]
[End of loop]
2. Exit.
Example:
Consider the array AUTO which records the number of automobiles sold each year from 1932
through 1984.
To find the number NUM of years during which more than 300 automobiles were sold, involves
traversing AUTO.
1. [Initialization step.] Set NUM := 0

2. Repeat for K = 1932 to 1984:

Page 18
DATA STRUCTURES AND APPLICATIONS

If AUTO [K] > 300, then: Set NUM: = NUM + 1.


[End of loop.]
3. Return.

2. Inserting
➢ Let A be a collection of data elements stored in the memory of the computer.

Inserting refers to the operation of adding another element to the collection A.


➢ Inserting an element at the “end” of the linear array can be easily done provided the memory
space allocated for the array is large enough to accommodate the additional element.
➢ Inserting an element in the middle of the array, then on average, half of the elements must be
moved downwards to new locations to accommodate the new element and keep the order of
the other elements.

Algorithm:
INSERT (LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that K ≤ N. This algorithm
inserts an element ITEM into the Kth position in LA.
1. [Initialize counter] set J:= N

2. Repeat step 3 and 4 while J ≥ K

3. [Move Jth element downward] Set LA [J+1] := LA[J]

4. [Decrease counter] set J:= J – 1


[End of step 2 loop]
5. [Insert element] set LA[K]:= ITEM

6. [Reset N] set N:= N+1

7. Exit

3. Deleting
➢ Deleting refers to the operation of removing one element to the collection A.
➢ Deleting an element at the “end” of the linear array can be easily done with difficulties.

Page 19
DATA STRUCTURES AND APPLICATIONS
➢ If element at the middle of the array needs to be deleted, then each subsequent elements be
moved one location upward to fill up the array.

Algorithm
DELETE (LA, N, K, ITEM)
Here LA is a linear array with N elements and K is a positive integer such that K ≤ N. this algorithm
deletes the Kth element from LA
1. Set ITEM:= LA[K]

2. Repeat for J = K to N – 1
[Move J + 1 element upward] set LA[J]:= LA[J+1]
[End of loop]
3. [Reset the number N of elements in LA] set N:= N – 1

4. Exit
Example: Inserting and Deleting
Suppose NAME is an 8-element linear array, and suppose five names are in the array, as in Fig.(a).
Observe that the names are listed alphabetically, and suppose we want to keep the array names
alphabetical at all times. Suppose Ford is added to the array. Then Johnson, Smith and Wagner must
each be moved downward one location, as in Fig.(b). Next suppose Taylor is added to the array; then
Wagner must be moved, as in Fig.(c). Last, suppose Davis is removed from the array. Then the five
names Ford, Johnson, Smith, Taylor and Wagner must each be moved upward one location, as in
Fig.(d).

Page 20
DATA STRUCTURES AND APPLICATIONS
4. Sorting
Sorting refers to the operation of rearranging the elements of a list. Here list be a set of n elements.
The elements are arranged in increasing or decreasing order.
Ex: suppose A is the list of n numbers. Sorting A refers to the operation of rearranging the elements
of A so they are in increasing order, i.e., so that,
A[I] < A[2] < A[3] < ... < A[N]
For example, suppose A originally is the list
8, 4, 19, 2, 7, 13, 5, 16
After sorting, A is the list
2, 4, 5, 7, 8, 13, 16, 19

Bubble Sort
Suppose the list of numbers A[l], A[2], ... , A[N] is in memory. The bubble sort algorithm works as
follows:
Algorithm: Bubble Sort – BUBBLE (DATA, N)
Here DATA is an array with N elements. This algorithm sorts the elements in
DATA.
1. Repeat Steps 2 and 3 for K = 1 to N - 1.
2. Set PTR: = 1. [Initializes pass pointer PTR.]
3. Repeat while PTR ≤ N - K: [Executes pass.]
(a) If DATA[PTR] > DATA[PTR + 1], then:
Interchange DATA [PTR] and DATA [PTR + 1].
[End of If structure.]
(b) Set PTR: = PTR + 1.
[End of inner loop.]
[End of Step 1 outer loop.]
4. Exit.

Example:

Page 21
DATA STRUCTURES AND APPLICATIONS

Page 22
DATA STRUCTURES AND APPLICATIONS
Complexity of the Bubble Sort Algorithm
The time for a sorting algorithm is measured in terms of the number of comparisons f(n). There are
n – 1 comparisons during the first pass, which places the largest element in the last position; there are
n - 2 comparisons in the second step, which places the second largest element in the next-to-last
position; and so on. Thus
f(n) = (n - 1) + (n - 2) + ... + 2 + 1 = 𝒏(𝒏−𝟏)/𝟐 = 𝒏𝟐/𝟐= O(n) = O(n2)

5. Searching
➢ Let DATA be a collection of data elements in memory, and suppose a specific ITEM of
information is given. Searching refers to the operation of finding the location LOC of ITEM
in DATA, or printing some message that ITEM does not appear there.
➢ The search is said to be successful if ITEM does appear in DATA and unsuccessful otherwise.

Linear Search
Suppose DATA is a linear array with n elements. Given no other information about DATA, The way
to search for a given ITEM in DATA is to compare ITEM with each element of DATA one by one.
That is, first test whether DATA [l] = ITEM, and then test whether DATA[2] = ITEM, and so on.
This method, which traverses DATA sequentially to locate ITEM, is called linear search or
sequential search.
Algorithm: (Linear Search) LINEAR (DATA, N, ITEM, LOC)
Here DATA is a linear array with N elements, and ITEM is a given item of information. This
algorithm finds the location LOC of ITEM in DATA, or sets LOC: = 0 if the search is unsuccessful.
1. [Insert ITEM at the end of DATA.] Set DATA [N + 1]: = ITEM.

2. [Initialize counter.] Set LOC: = l.

3. [Search for ITEM.]


Repeat while DATA [LOC] ≠ ITEM:
Set LOC:= LOC + 1.
[End of loop.]
4. [Successful?] If LOC = N + 1, then: Set LOC:= 0

5. Exit.

Page 23
DATA STRUCTURES AND APPLICATIONS
Complexity of the Linear Search Algorithm
Worst Case: The worst case occurs when one must search through the entire array DATA, i.e., when
ITEM does not appear in DATA. In this case, the algorithm requires comparisons.
f(n) = n + 1
Thus, in the worst case, the running time is proportional to n.
Average Case: The average number of comparisons required to find the location of ITEM is
approximately equal to half the number of elements in the array.
f(n)= (𝑛+1)/2

Binary Search
Suppose DATA is an array which is sorted in increasing numerical order or, equivalently,
alphabetically. Then there is an extremely efficient searching algorithm, called binary search, which
can be used to find the location LOC of a given ITEM of information in DATA.

Algorithm: (Binary Search) BINARY (DATA, LB, UB, ITEM, LOC)


Here DATA is a sorted array with lower bound LB and upper bound UB, and ITEM is a given
item of information. The variables BEG, END and MID denote, the beginning, end and middle
locations of a segment of elements of DATA.
This algorithm finds the location LOC of ITEM in DATA or sets LOC = NULL.
1. [Initialize segment variables.]
Set BEG: = LB, END := UB and MID = INT((BEG + END)/2).
2. Repeat Steps 3 and 4 while BEG ≤ END and DATA [MID] ≠ ITEM.

3. If ITEM < DATA [MID], then:


Set END := MID - 1.
Else:
Set BEG := MID + 1.
[End of If structure.]
4. Set MID := INT((BEG + END)/2).
[End of Step 2 loop.]
5. If DATA[MID] = ITEM, then:
Set LOC := MID.
Else:
Page 24
DATA STRUCTURES AND APPLICATIONS
Set LOC := NULL.
[End of If structure.]
6. Exit.
Complexity of the Binary Search Algorithm
The complexity is measured by the number f(n) of comparisons to locate ITEM in DATA where
DATA contains n elements. Observe that each comparison reduces the sample size in half. Hence we
require at most f(n) comparisons to locate ITEM where
f(n) = [log2 n] + 1
That is, the running time for the worst case is approximately equal to log2 n. One can also show that
the running time for the average case is approximately equal to the running time for the worst case.

MULTIDIMENSIONAL ARRAY
Two-Dimensional Arrays
A two-dimensional m x n array A is a collection of m . n data elements such that each element is
specified by a pair of integers (such as J, K), called subscripts, with the property that
1 ≤ J ≤ m and 1 ≤ K ≤ n
The element of A with first subscript j and second subscript k will be denoted by
AJ,K or A[J, K]
Two-dimensional arrays are called matrices in mathematics and tables in business applications.
There is a standard way of drawing a two-dimensional m x n array A where the elements of A form
a rectangular array with m rows and n columns and where the element A[J, K] appears in row J and
column K.

Representation of Two-Dimensional Arrays in Memory


Let A be a two-dimensional m x n array. Although A is pictured as a rectangular array of elements
with m rows and n columns, the array will be represented in memory by a block of m . n sequential
memory locations.
Page 25
DATA STRUCTURES AND APPLICATIONS
The programming language will store the array A either (1) column by column, is called column-
major order, or (2) row by row, in row-major order.

Polynomials
• A polynomial is a sum of terms, where each term has a form axe,
Where x=variable, a=coefficient and e=exponent.
For ex,
A(x)=3x20+2x5+4 and B(x)=x4+10x3+3x2+1
• The largest (or leading) exponent of a polynomial is called its degree.
• Assume that we have 2 polynomials,
A(x)= ∑ai xi &
B(x)= ∑bi xi then A(x)+B(x)= ∑(ai + bi)xi

POLYNOMIAL REPRESENTATION: FIRST METHOD

#define MAX_DEGREE 100


typedef struct
{
int degree;
float coef[MAX_DEGREE];
}polynomial;

polynomial a;

Page 26
DATA STRUCTURES AND APPLICATIONS

Initial version of padd function

/* d =a + b, where a, b, and d are polynomials */


d = Zero( )
while (! IsZero(a) && ! IsZero(b)) do
{
switch COMPARE (Lead_Exp(a), Lead_Exp(b))
{
case -1: d = Attach(d, Coef (b, Lead_Exp(b)), Lead_Exp(b));
b = Remove(b, Lead_Exp(b));
break;
case 0: sum = Coef (a, Lead_Exp (a)) + Coef ( b, Lead_Exp(b));
if (sum)
{
Attach (d, sum, Lead_Exp(a));
a = Remove(a , Lead_Exp(a));
b = Remove(b , Lead_Exp(b));
}
break;
case 1: d = Attach(d, Coef (a, Lead_Exp(a)), Lead_Exp(a));
a = Remove(a, Lead_Exp(a));
}
}
insert any remaining terms of a or b into d

• If a is of type ‘polynomial’ then A(x)= ∑ai xi can be represented as:


a.degree=n a.coeff[i]=a n-i
• In this representation, we store coefficients in order of decreasing exponents, such that a.coef[i]
is the coefficient of xn-i provided a term with exponent n-i exists; otherwise, a.coeff[i]=0
• Disadvantage: This representation wastes a lot of space. For instance, if a.degree<<MAX_DEGREE
and polynomial is sparse, then we will not need most of the positions in a.coef[MAX_DEGREE]
(sparse means number of terms with non-zero coefficient is small relative to degree of the
polynomial).

POLYNOMIAL REPRESENTATION: SECOND METHOD


#define MAX_TERMS 100
typedef struct
{ float coef;
int expon;
}polynomial;

Page 27
DATA STRUCTURES AND APPLICATIONS
polynomial terms[MAX_TERMS];
int avail=0;
• A(x)=2x1000+1 and B(x)=x4+10x3+3x2+1 can be represented as shown below.

Fig A. Array representation of two polynomials

• startA & startB give the index of first term of A and B respectively.
• finishA & finishB give the index of the last term of A & B respectively.
avail gives the index of next free location in the array.
• Any polynomial A that has ‘n’ non-zero terms has startA & finishA such that finishA=startA+n-1
• Advantage: This representation solves the problem of many 0 terms since A(x)-2x1000+1 uses only
6 units of storage (one for startA, one for finishA, 2 for the coefficients and 2 for the exponents)
• Disadvantage: However, when all the terms are non-zero, the current representation requires
about twice as much space as the first one.

POLYNOMIAL ADDITION

Function to add two polynomials


void padd (int starta, int finisha, int startb, int finishb,int * startd, int *finishd)
{
/* add A(x) and B(x) to obtain D(x) */ float coefficient;
*startd = avail;
while (starta <= finisha && startb <= finishb)
{
switch (COMPARE(terms[starta].expon, terms[startb].expon))
{
case -1: /* a expon < b expon */
attach(terms[startb].coef, terms[startb].expon);
startb++
break;
case 0: /* equal exponents */
coefficient = terms[starta].coef + terms[startb].coef;
if (coefficient)
attach (coefficient, terms[starta].expon);
starta++;
startb++;

Page 28
DATA STRUCTURES AND APPLICATIONS
break;
case 1: /* a expon > b expon */
attach(terms[starta].coef, terms[starta].expon); starta++;
}
}
/* add in remaining terms of A(x) */
for( ; starta <= finisha; starta++)
attach(terms[starta].coef, terms[starta].expon);
/* add in remaining terms of B(x) */
for( ; startb <= finishb; startb++)
attach(terms[startb].coef, terms[startb].expon);
*finishd =avail -1;

Function to add a new term

void attach(float coefficient, int exponent)


{
/* add a new term to the polynomial */
if (avail >= MAX_TERMS)
{
fprintf(stderr, “Too many terms in the polynomial\n”);
exit(0);
}
terms[avail].coef = coefficient;
terms[avail++].expon = exponent;
}
SPARSE MATRICES
• Sparse matrix contains many zero entries.
• When a sparse matrix is represented as a 2-dimensional array, we waste space.
• For ex, if 100*100 matrixes contain only 100 entries then we waste 9900 out of 10000 memory
spaces.
• Solution: Store only the non-zero elements.

Page 29
DATA STRUCTURES AND APPLICATIONS

SPARSE MATRIX REPRESENTATION


• We can classify uniquely any element within a matrix by using the triple <row,col,value>.
Therefore, we can use an array of triples to represent a sparse matrix.

SpareMatrix Create(maxRow,maxCol) ::=

#define MAX_TERMS 101

typedef struct term

int col;

int row;

int value;

} term;

term a[MAX_TERMS];

Sparse matrix and its transpose stored as triples

• a[0].row contains the number of rows; a[0].col contains number of columns and
a[0].value contains the total number of nonzero entries.

Page 30
DATA STRUCTURES AND APPLICATIONS

TRANSPOSING A MATRIX
• To transpose a matrix, we must interchange the rows and columns.
• Each element a[i][j] in the original matrix becomes element b[j][i] in the transpose matrix.
• Algorithm To transpose a matrix:
for all elements in column j
place element <i,j,value>
in element <j,i,value>

TRANSPOSE OF A SPARSE MATRIX

void transpose (term a[], term b[])


{
/* b is set to the transpose of a */
int n, i, j, currentb;
n = a[0].value; /* total number of elements */
b[0].row = a[0].col; /* rows in b = columns in a */ b[0].col
= a[0].row; /*columns in b = rows in a */ b[0].value = n;
if (n > 0)
{ /*non zero matrix */
currentb = 1;
for (i = 0; i < a[0].col; i++) /* transpose by columns in a */
for( j = 1; j <= n; j++) /* find elements from the current column */
if (a[j].col == i)
{ /* element is in current column, add it to b */
b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++
}
}
}

Page 31
DATA STRUCTURES AND APPLICATIONS

Page 32
DATA STRUCTURES AND APPLICATIONS
ADT

Page 33
DATA STRUCTURES AND APPLICATIONS

Page 34

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy