1st Module
1st Module
MODULE 1
INTRODUCTION TO DATA STRUCTURES
• “A data structure is a method of storing and organizing the data in a computer so that
it can be used efficiently”.
• 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.
• If the data contains a single value, then it can be represented using primitive data types.
• If the data contains set of values, then it can be represented using non-primitive data
types.
The computers are electronics data processing machines. In order to solve a particular problem
we need to know:
1. How to represent data in a computer.
2. How to access them.
3. What are the steps to be performed in order to get the needed output.
These tasks can be achieved with the knowledge of Data structures & Algorithms.
1
Data Structures and Applications Dept of CS&D
Integer
Primitive Floating Point
Character
Double
Pointer
Data Structure
Arrays
Stacks
Linear
Queues
Linked List
Non-Primitive
Trees
2
Non-Linear
Graphs
Data Structures and Applications Dept of CS&D
Primitive Data Structures are the basic data structures that directly operate upon the machine
instructions. They have different representations on different computers. Integers, floating point
numbers, character constants, string constants and pointers come under this category.
Non-primitive data structures are more complicated data structures and are derived from
primitive data structures. They emphasize on grouping same or different data items with
relationship between each data item. Arrays, lists and files come under this category.
A data structure is said to be linear if its elements form a sequence or a linear list. The
linear data structures like an array, stacks, queues and linked lists organize data in linear order.
There are basically four ways of representing such linear structure in memory.
1. Arrays: An array is a collection of similar type of items (elements) stored sequentially
(continuously) one after the other in memory.
2. Stack: A stack is an ordered list in which insertions and deletions are made at one end called
the top.
3. Queue: A queue is an ordered list in which insertions and deletions take place at different
ends.”
4. Linked list: Linked list is a linear data structure that consists of a sequence of elements where
each element comprises of two items - the data and a reference (link) to the next node
A data structure is said to be non-linear if the data are not arranged in sequence or linear.
The insertion and deletion of data is not possible in linear fashion. i.e.,elements form a
hierarchical classification where, data items appear at various levels.
1.Trees: Tree is a non-linear data structure which organizes data in hierarchical fashion and the
tree structure follows a recursive pattern of organizing and storing data.
2. Graph: It is basically a collection of vertices (also called nodes) and edges that connect these
vertices.
3
Data Structures and Applications Dept of CS&D
1. Traversing: It is used to access each data item exactly once so that it can be processed.
2. Searching: It is used to find the location of the data item with a given key value or finding the
locations of all data which satisfy one or more conditions.
3. Inserting: It is used to add a new data item in the given collection of data items.
4. Deleting: It is used to delete an existing data item from the given collection of data items.
5. Sorting: It is used to arrange the data items in some logical order. e.g., in ascending or
descending order in case of numerical data and in dictionary order in case of alphanumeric data.
6. Merging: It is used to combine the data items of two sorted files into single file in the sorted
form.
1.4.1 Arrays
An Array is a special and powerful data structure and it is used to store, process and print large
amounts of data.
“An array is a collection of similar type of items (elements) stored sequentially
(continuously) one after the other in memory”.
A[0] 10
A[1] 20
A[2] 30
A[3] 40
A[4] 50
The Elements in the Array A can be accessed using the common name A, but with different
index.
The Element “10” is called 0th Element and it can be accessed using the Subscript 0 (called
Index “0”) along with name of the array “A”.
4
Data Structures and Applications Dept of CS&D
Where,
data_type: data type can be int, float, char etc.
array_name: name of the array which is a valid C variable.
size: it is the number of elements in the array.
Complete declaration ends with Semicolon.
5
Data Structures and Applications Dept of CS&D
char name[5];
6
Data Structures and Applications Dept of CS&D
A[0] 10
A[1] 20
A[2] 30
A[3] 40
A[4] 50
list[i] = α + i * sizeof(int)
Where, α is base address.
7
Data Structures and Applications Dept of CS&D
a. The elements of the array are referenced respectively by an index set consisting of n
consecutive numbers.
b. The elements of the array are respectively in successive memory locations.
The number n of elements is called the length or size of the array. The length or the numbers of
elements of the array can be obtained from the index set by the formula
When LB = 0,
Length = UB – LB + 1
When LB = 1,
Length = UB
Where,
UB is the largest index called the Upper Bound
LB is the smallest index, called the Lower Bound
1000
2000
3000
4000
5000
1.5.1 Traversing
Let array 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 array A it can be accomplished by Traversing.
Traversing is a accessing and processing each element in the array exactly once.
If you want to read n data items from the keyboard, the following statement can be used:
for(i=0;i<5;i++)
{
scanf(“%d”,&a[i]);
}
//If you want to print „n‟ data items from the keyboard, the following statement can be used:
for(i=0;i<5;i++)
{
printf(“%d\n”, a[i]);
}
1.5.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 array 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:
1. Start
2. Read pos, elem.
3. Create space for item to insert at position
for(i=n-1;i>=pos;i- -)
{
A[i+1] = A[i];
}
9
Data Structures and Applications Dept of CS&D
6. Stop
Int A[5]={10,20,30,40,50};
10
Data Structures and Applications Dept of CS&D
1.5.3 Deletion
Deleting refers to the operation of removing one element from the array A with specified position.
Algorithm:
1. Start
2. Read pos.
6. Stop
11
Data Structures and Applications Dept of CS&D
12
Data Structures and Applications Dept of CS&D
• The size used during declaration of the array is useful to reserve the
specified memory locations.
row_size row 0
row 1
array_name
• The array “a” is a 2-dimensional array with 2 rows and 4 columns. This
declaration informs the compiler to reserve 8 locations (2*4=8 locations, 2*8=16 bytes in
total) continuously one after the other.
Syntax:
data_type array_name[row_size][col_size]={
{a1,a2, ---- ,an},
{b1,b2, ---- ,bn},
……………...,
{z1,z2, ---- ,zn}
};
a1 to an are the values assigned to 1st row, b1 to bn are the values assigned to 2nd row and so
on.
0 1 2
0 11 22 33
44 55 66
1
77 88 99
Rows 2
3 10 20 30
1. Row major order: the elements are stored row by row one row at a time.
14
Data Structures and Applications Dept of CS&D
2. Column major order: the elements are stored column by column one column at a time.
1. Linear Search: linear search or sequential search is a method for finding an element within a
list. It sequentially checks each element of the list until a match is found or the whole list has been
searched.
✓ Linear search is usually very simple to implement, and is practical when
the list has only a few elements, or when performing a single search in an unordered list.
A simple approach is to do linear search
• Start from the leftmost element of arr[] and one by one compare j with each element of
arr[].
• If j matches with an element, return the index number.
• If j doesn‟t match with any of elements, return -1 or element not found in an arr[].
A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
15
Data Structures and Applications Dept of CS&D
Example: C Program to search the „key‟ element in an array using linear search algorithm.
#include <stdio.h>
void main()
{
int array[100], key, i, n;
printf("Enter number of elements in array\n"); scanf("%d", &n);
printf("Enter elements of array\n"); for (i = 0; i < n; i++)
scanf("%d", &array [ i ] );
printf("Enter a number to search\n"); scanf("%d", &key);
for (i = 0; i < n; i++)
{
}
if (i == n)
if (array[i] == key)
{
printf("%d is present at location %d.\n", key, i+1);
break;
}
printf("%d isn't present in the array.\n", key);
}
Output:
Enter number of elements in array:5
Enter elements of array 100
25
35
30
56
Enter a number to search: 30
30 is present at location 4
2. Binary Search:
If the target value is less than the middle element, the search continues in the lower half of the
array. If the target value is greater than the middle element, the search continues in the upper half
of the array.
For a binary search to work, it is mandatory for the target array to be sorted. The following is our
sorted array and let us assume that we need to search the location of value 31 using binary search.
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
Now we compare the value stored at location 4, with the value being searched, i.e. 31. We find
that the value at location 4 is 27, which is not a match. As the value is greater than 27 and we have
a sorted array, so we also know that the target value must be in the upper portion of the array.
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
We change our low to mid + 1 and find the new mid value again.
low = mid + 1
mid = low + (high - low) / 2
Our new mid is 7 now. We compare the value stored at location 7 with our target value 31.
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
17
Data Structures and Applications Dept of CS&D
The value stored at location 7 is not a match; rather it is more than what we are looking for. So,
the value must be in the lower part from this location.
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
We compare the value stored at location 5 with our target value. We find that it is a match.
10 14 19 26 27 31 33 35 42 44
0 1 2 3 4 5 6 7 8 9
Binary search halves the searchable items and thus reduces the count of comparisons to be made
to very less numbers.
Example: C Program to search key elements in array using binary search algorithms.
18
Data Structures and Applications Dept of CS&D
{
printf("%d found at location %d\n", key, middle+1); break;
}
else if ( arr[middle] < key)
{
first = middle + 1;
}
else
{
last = middle - 1;
}
middle = (first + last)/2;
}
if(first > last)
{
printf("Not found! %d is not present in the list.",key);
}
}
1. Bubble Sort.
✓ Bubble Sort is the simplest sorting algorithm that works by repeatedly swapping the adjacent
elements if they are in wrong order.
✓ Bubble sort algorithm starts by comparing the first two elements of an array and swapping if
necessary, i.e., if you want to sort the elements of array in ascending order and if the first element
is greater than second then, you need to swap the elements but, if the first element is smaller than
second, you mustn't swap the element.
✓ If there are n elements to be sorted then, the process mentioned above should be repeated n-1
times to get required result. But, for better performance, in second step, last and second last
elements are not compared because; the proper element is automatically placed at last after first
step. Similarly, in third step, last and second last and second last and third last elements are not
compared and so on.
19
Data Structures and Applications Dept of CS&D
Example: C Program to sort the given array elements using Bubble sort Algorithm.
#include<stdio.h>
void main()
{
int a[50],n,i,j,temp;
printf("Enter the size of array: "); scanf("%d",&n);
printf("Enter the array elements: "); for(i=0;i<n;++i) scanf("%d",&a[i]); for(i=1;i<n;++i)
for(j=0;j<(n-i);++j)
if(a[j]>a[j+1])
{
temp=a[j]; a[j]=a[j+1]; a[j+1]=temp;
}
printf("\nArray after sorting: "); for(i=0;i<n;++i)
printf("%d ",a[i]);
}
Output:
Enter the size of array: 5
Enter elements of array
30
25
35
10
56
Sorted elements:
10
25
30
35
56
20
Data Structures and Applications Dept of CS&D
3.1 STRINGS
“A string is a sequence of characters enclosed within double quotes”.
or
B I E T \0
A[0] A[1] A[2] A[3] A[4]
Where,
Example
1. char name[21];
Size of the string is 21, means that it can store up to 20 characters plus one null character.
2. char str[10];
Size of the string is 10, means that it can store up to 10 characters plus one null character.
21
Data Structures and Applications Dept of CS&D
Examples:
1. char a[9]={“C”, “O”, “M”, “P”, “U”, “T”, “E”, “R”, “\0”};
The compiler allocates 9 memory locations ranging from 0 to 8 and these locations are
initialized with the characters in the order specified.
a C O M P U T E R \0
0 1 2 3 4 5 6 7 8
2. char a[ ]={“C”, “O”, “M”, “P”, “U”, “T”, “E”, “R”, “\0”};
For this declaration, the compiler will set the array size to the total number of initial values.
i.e. 9. The characters will be stored in these memory locations in the order specified as shown
below:
a C O M P U T E R \0
0 1 2 3 4 5 6 7 8
3. char a[ ]= “COMPUTER”;
Here, the string length is 8 bytes. But string size is 9 bytes. So, the compiler reserves 8+1
memory locations and these locations are initialized with the characters in the order specified. The
string is terminated by “\0” by the compiler.
a C O M P U T E R \0
22
Data Structures and Applications Dept of CS&D
The scanf() function stops reading characters when it finds the first white space character (
spaces, tabs and new line characters).
This type of I/O functions processes entire line (string with white spaces). Hence these are called
line- oriented I/O.
gets() function is used to read a sequence of characters (string) with spaces in between.
The “gets()” function allows us to read an “entire line” of input including whitespace characters.
23
Data Structures and Applications Dept of CS&D
Whenever we want to display a sequence of characters stored in memory locations on the screen,
then puts() function can be used.
Syntax: puts(string);
24
Data Structures and Applications Dept of CS&D
3.6.1 Substring: Accessing a substring from a given string requires three pieces of information:
(1) The name of the string or the string itself.
(2) The position of the first character of the substring in the given string.
(3) The length of the substring or the position of the last character of the substring.
The syntax denotes the substring of a string S beginning in a position K and having a length L.
3.6.2 Indexing: Indexing also called pattern matching, refers to finding the position where a
string pattern P first appears in a given string text T. This operation is called INDEX.
If the pattern P does not appears in the text T, then INDEX is assigned the value 0. The arguments
“text” and “pattern” can be either string constant or string variable.
4.1 Structures
Structure is a user defined data type that can hold data items of same/different data types.
All data items grouped are logically related & can be accessed by using variables.
Declaration:
Syntax:
struct tag-name
{
data_type member 1;
data_type member 2;
………………………
………………………
data_type member n;
};
In this declaration, struct is a required keyword, tag-name is a name of the structure defined.
The individual members can be ordinary variables, pointers, arrays or other structures. The
member names within a particular structure must be distinct from one another.
25
Data Structures and Applications Dept of CS&D
To allocate the memory for the structure, we have to declare the variable as shown below:
Struct student s1,s2; [ size of variables s1,s2 is 22bytes each] Two ways to declare variables:
Ex: Method-1
struct person
{
char name[10]; int age;
float salary;
}p;
strcpy(p.name,“james”); p.age = 10;
p.salary = 35000;
Method-2
struct student
{
char name[10]; int age;
float marks;
}s1={“virat”,19,25};
26
Data Structures and Applications Dept of CS&D
Reading:
printf(“Enter name of the student\n”);
scanf(“%s”,&s.name);
printf(“Enter marks of the student\n”);
scanf(“%f”,&s.marks);
Writing:
printf(“name of the student is %s\n”,s.name);
printf(“marks of the student is %f\n”,s.marks);
Example: The following example shows two structures, where both the structure are defined
separately.
Struct
{
int month;
int day;
int year;
}date;
A person born on February 11, 1944, would have the values for the date struct set as:
person1.dob.month = 2;
person1.dob.day = 11;
person1.dob.year = 1944;
27
Data Structures and Application Dept of CS&D
Example:
A person born on February 11, 1944, would have the values for the date struct
set as: person1.dob.month = 2;
person1.dob.day = 11;
person1.dob.year = 1944;
typedefstruct
{
char name[10];
int age;
float salary;
struct
{
int month;
int day;
int year;
} date;
} humanBeing;
Consider as an example:
Struct
{
char data;
struct list *link ;
} list;
Each instance of the structure list will have two components data and link.
data: is a single character,
link: link is a pointer to a list structure. The value of link is either the address in
memory of an instance of list or the null pointer.
28
Data Structures and Application Dept of CS&D
Consider these statements, which create three structures and assign values to
their respective fields: list item1, item2, item3;
item1.data = 'a';
item2.data = 'b';
item3.data = 'c';
item1.link = item2.1ink = item3.link = NULL;
a b c
Structure variables item1, item2 and item3 each contain the data items a, b, and
c respectively, and the null pointer. These structures can be attached together by
replacing the null link field in item 2 with one that points to item 3 and by
replacing the null link field in item 1 with one that points to item 2.
item1.link = &item2;
item2.1ink = &item3;
a b c
4.4 Unions
Syntax:
union tag-name
{
data_type member 1;
data_type member 2;
………………………
………………………
data_type member n;
};
29
Data Structures and Application Dept of CS&D
Example:
data_type member 1;
data_type member 2;
………………………
……………………… data_type member n;
unionstudent
{
char name[10]; intage;;
float salary;
};
0 1 2 3 4 5 6 7
name
age
salary
The major difference between a union and a structure is that unlike structure
members which are stored in separate memory locations; all the members of
union must share the same memory space. This means that only one field of the
union is "active" at any given time.
#include <stdio.h>
struct student
{
int marks; char grade;
float percentage;
};
void main()
{
30
Data Structures and Application Dept of CS&D
#include <stdio.h>
union student
{
int marks; char grade;
float percentage;
};
void main()
{
union student s1;
s1.marks=29;
printf(" Marks= %d \n", s1.marks);
s1.grade=‟A‟;
printf(" Grade= %c \n", s1.grade);
s1.percentage=99.5;
printf("Percentage = %c \n", s1.percentage);
}
C Structure C Union
Structure allocates storage space for Union allocates one common storage
all its members seperately space for all its members. Union finds
that which of its member needs high
storage space over other members and
allocates that much space.
31
Data Structures and Application Dept of CS&D
5.1 Pointers
3. We can’t change these addresses assigned by the system & hence these are
constant. But we can only use them to store the data.
Data
Address
10
20
30
32
Data Structures and Application Dept of CS&D
40
0 50
1 …
2 …
3 … MEMORY
4 ... LOCATION
5
S
…..
65534
65535
Definition
“A pointer is a variable which contains the address of another variable as
its value”.
where,
data_type: It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
pointer_variable_name: It is the name of the pointer variable.
Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. float *temp; // declares a pointer variable temp of floating type.
33
Data Structures and Application Dept of CS&D
i. The Address of operator (&): By using the address of (&) operator, we can
determine the address of the variable.
ii. The Indirection operator (*): It gives the value stored at a particular
address.
int a=3;
int *ptr;
ptr=&a;
Memory layout:
Ptr a
65530 3
Address:65530
Ptr=&a copies the address of “a” to the pointer variable “ptr”.
#include<stdio.h>
#include<conio.h>
void main ()
{
int a=20, *ptr1;
clrscr ();
ptr1 = &a; //ptr1 is a pointer to variable a
printf(“The address of a=%d and value of a=%d\n”,ptr1,*ptr1);
getch();
}
Memory layout:
Ptr1 a
65530 20
34
Data Structures and Application Dept of CS&D
We can initialize the pointer variables by assigning the address of other variable
to them. However these variables must be declared in the program.
Syntax
where,
data_type:. It can be int, float, char etc.
Asterisk (*): It tells the compiler that we are declaring a pointer variable.
pointer_variable_name: It is the name of the pointer variable.
address_of_variable: It is the address of another variable.
Example:
1. int a;
int *ptr;
ptr=&a;
or
int a;
int *ptr=&a; Both are equivalent.
Memory can be reserved for the variables either during compilation time
or during execution time (run time).
Based on this memory can be allocated for variables using two different
techniques:
1. Static allocation
2. Dynamic allocation
Static Allocation
35
Data Structures and Application Dept of CS&D
Dynamic Allocation
where,
ptr: ptr is a pointer variable of type int, float, char, double etc.
data_type: It can be any of the basic data type or user defined data type.
size: size is the number of bytes to be reserved for a block.
Example:
1. ptr = (int *) malloc(10);
Allocates a block of Memory of 10 bytes.
where,
ptr: ptr is a pointer variable of type int, float, char, double etc.
data_type: It can be any of the basic data type or user defined data type.
n: n is the number of blocks to be allocated.
size: size is the number of bytes in each block.
Example:
1. ptr = (int *) calloc(10, 2);
Allocates 10 blocks of Memory each of 2 bytes.
37
Data Structures and Application Dept of CS&D
where,
ptr: it is a pointer to a block of previously allocated memory either using
malloc( ) or calloc( ).
data_type: It can be any of the basic data type or user defined data type.
new_size: it is the new size of the block.
Example:
char *str;
str = (char *) malloc(10); // malloc function allocates 10 memory blocks
strcpy(str, “Computer”);
str = (char *) realloc (str, 40); //realloc function allocates new memory
blocks from 10 to 40 strcpy(str, “Computer Science and Engineering”);
Syntax free(ptr);
Ex:int *ptr;
ptr = (int *) malloc(100*sizeof(int)); free(ptr);
38
Data Structures and Application Dept of CS&D
Memory size can’t be modified while Memory size can be modified while
execution execution
Example:Array
Example:Linked List
Malloc( ) Calloc( )
5.4 Polynomials
39
Data Structures and Application Dept of CS&D
Polynomial operations
1. Representation
2. Addition
3. Multiplication
2 1 1 10 3 1 Coef
1000 0 4 3 2 0
exp
0 1 2 3 4 5 6
The above figure shows how these polynomials are stored in the array
terms.
The index of the first term of A and B is given by startA and startB, while
finishA and finishB give the index of the last term of A and B.
The index of the next free location in the array is given by avail.
For above example, startA=0, finishA=1, startB=2, finishB=5, & avail=6.
To produce D (x), padd( ) is used to add A (x) and B (x) term by term. Starting
at position avail, attach( ) which places the terms of D into the array, terms.
If there is not enough space in terms to accommodate D, an error message is
printed to the standard error device & exits the program with an error condition.
void main( )
{
POLY p1[20],p2[20],p3[20];
int m,n,k;
printf(“Enter the 1st polynomial:”);
scanf(%d”,&m);
readpoly(p1,m);
printf(“Enter the 2nd polynomial:”);
scanf(“%d”,&n);
readpoly(p2,n);
printf(“poly 1:”);
printpoly(p1,m);
printf(“poly 2:”);
k=addpoly(p1,m,p2,n,p3);
printf(“poly 3:”);
printpoly(p3,k);
}
readpoly(POLY p1,int m)
{
int i,cf,px;
for(i=0;i<n;i++)
{
printf(“cf,px”);
p[i].cf=cf;
41
Data Structures and Application Dept of CS&D
p[i].px=px;
}
}
}
}
return k;
}
43
Data Structures and Application Dept of CS&D
Positions 1 through 8 store the triples representing the nonzero entries. The row
index is in the field row, the column index is in the field col, and the value is in
the field value. The triples are ordered by row and within rows by columns.
44
Data Structures and Application Dept of CS&D
45
Data Structures and Application Dept of CS&D
46
Data Structures and Application Dept of CS&D
}
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.
This can be avoided by using the column indices to determine the placement of
elements in the transpose matrix. This suggests the following algorithm:
The columns within each row of the transpose matrix will be arranged in
ascending order.
b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++;
}
}
}
PATTREN MATCHING
Analysis: The while loop is iterated until the end of either the string or the
pattern is reached. Since i is never decreased, the lines that increase i cannot be
executed more than m=strlen(string) times. The resetting of j to failure [j-1]+1
decreases the value of j. so, this can‟t be done more times than j is incremented
by the statement j++ as otherwise, j falls off the pattern. Each time the statement
j++ is executed, i is also incremented. So, j can‟t be incremented more than m
times. No statement of code is executed more than m times.
return ((j == lenp) ? (i - lenp) : -1 )
48
Data Structures and Application Dept of CS&D
This statement checks to see whether or not we found the pattern. If we didn‟t
find the pattern, the pattern index j is not equal to the length of the pattern and
we return -1. If we found the pattern, then the starting position is i the length
of the pattern.
P and T are strings with lengths R and S, and are stored as arrays with one
character per element. This algorithm finds the INDEX of P in T.
1.[Initialize.]
Set K= 1 and MAX= S - R + 1
2. Repeat Steps 3 to 5
while K ≤ MAX
3. Repeat for L = 1 to R [Tests each character of P] If P[L] ≠ T[K + L – l], then:
49
Data Structures and Application Dept of CS&D
Observation of algorithms
P is an r-character string and T is an s-character string. Algorithm contains two
loops, one inside the other. The outer loop runs through each successive R-
character substring WK = T[K] T[K + 1] ... T[K+R-l] of T. The inner loop
compares P with WK, character by character. If any character does not match,
then control transfers to Step 5, which increases K and then leads to the next
substring of
T. If all the R characters of P do match those of some WK then P appears in T
and K is the INDEX of P in T. If the outer loop completes all of its cycles, then
P does not appear in T and so INDEX = 0.
1. STACKS:
Definition
“A stack is an ordered list in which insertions (pushes) and deletions (pops) are made at one end
called the top.”
Given a stack S= (a0, ... ,an-1), where a0 is the bottom element, an-1 is the top element, and ai is
on top of element ai-1, 0 < i < n.
50
Data Structures and Application Dept of CS&D
As shown in above figure, the elements are added in the stack in the order A, B, C, D, E, then E
is the first element that is deleted from the stack and the last element is deleted from stack is A.
Figure illustrates this sequence of operations.
Since the last element inserted into a stack is the first element removed, a stack is also known as
a Last-In-First-Out (LIFO) list.
51
Data Structures and Application Dept of CS&D
Push( )
Function push checks whether stack is full. If it is, it calls stackFull( ),
which prints an error message and terminates execution. When the stack is not
full, increment top and assign item to stack [top].
void push()
{
if (top >= STACK_SIZE-1)
{
stackFull();
}
else
{
printf(“enter the element to be pushed on to stack\n”);
scanf(“%d”,&item);
top= top+1;
stack[top] = item;
}
}
Pop( )
Deleting an element from the stack is called pop operation. The element
is deleted only from the top of the stack and only one element is deleted at a
time
void pop ( )
{
if (top == -1)
{
return stackEmpty();
}
else
{
item= stack[top]; top= top-1;
printf(“deleted element is %d\n”,item);
}
}
52
Data Structures and Application Dept of CS&D
Display( )
void Display( )
{
int i;
if(top==-1)
{
printf(“stack is full”);
return;
}
printf(“contents of the stack\n”);
for(i=0;i<=top;i++)
printf(“%d\n”,s[i]);
}
if (top SIZE-1)
{
printf("Stack overflow\n");
return;
}
But, once the stack is full, instead of returning the control, we can increase the
size of array realloc() function and the above code can be modified as shown
below:
if (top-SIZE-1)
{
printf("Stack Full: update size, insert item'n ");
SIZE++;
s = (int*) realloc(s, SIZE*sizeof(int));
}
53
Data Structures and Application Dept of CS&D
When above condition fails, it means we can insert an item. If the above
condition is true, spe what sufficient. So, using realloc() we increase the size by
1 and we can insert an item. To inser an item, we have to increment top by 1 as
shown below:
top=top + 1;
s[top]=item;
2. EXPRESSIONS:
It is sequence of operators and operands that reduces to a single value after
evaluation is called an expression.
X=a/b–c+d*e–a*c
above expression contains operators (+, –, /, *) operands (a, b, c, d, e).
Types of Expressions
Prefix Expression or Polish notation
Infix Expression
Postfix Expression or Reverse Polish notation
54
Data Structures and Application Dept of CS&D
Infix Expression:
In this expression, the binary operator is placed in-between the operand. The
expression can be parenthesized or un- parenthesized.
Example:
Infix expression A+B
The rules that determine the order in which different operators are evaluated are
called precedence rules or precedence of operators.
In an expression,If two or more operators have the same priority and are
evaluated from left-to right,then the operators are called left associative
operator.
In an expression,If two or more operators have the same priority and are
evaluated from right-to left,then the operators are called right associative
operator.
55
Data Structures and Application Dept of CS&D
56
Data Structures and Application Dept of CS&D
57
Data Structures and Application Dept of CS&D
The first operand popped is operand2 and the second operand popped is
operand1.
4. Perform the desired operation and push the result onto stack
5. Repeat above steps till the end of the expression reached.
58
Data Structures and Application Dept of CS&D
59
Data Structures and Application Dept of CS&D
60