DS Module 1
DS Module 1
Module -1
Introduction
1.1 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.
Dept. of CS&E,JIT-DVG 1
DATASTRUCTURE AND APPLICATIONS
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.
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.
Graph: It is basically a collection of vertices (also called nodes) and edges that connect these
vertices.
Dept. of CS&E,JIT-DVG 2
DATASTRUCTURE AND APPLICATIONS
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‟.
An „Index‟ is also called as Subscript ([ ]). It is used to indicate the position of an element in the
Array.
Dept. of CS&E,JIT-DVG 3
DATASTRUCTURE AND APPLICATIONS
1000 35 Marks[0]
data type array_name 1002 45 Marks[1]
1004 65 Marks[2]
1006 55 Marks[3]
75
char name[5]; 1008 Marks[4]
5 memory locations are reserved. sizeof(int) is 2 bytes, 2*5=10 bytes are reserved.
5 memory locations are reserved. sizeof(char) is 1 bytes 1*5=5 bytes are reserved.
Dept. of CS&E,JIT-DVG 4
DATASTRUCTURE AND APPLICATIONS
a[0] 10
a[1] 20
a[2] 30
a[3] 40
a[4] 50
list[i] = α + i * sizeof(int)
For example, an array of 10 integer variables, with indices 0 through 9, may be stored as 10 words at
memory addresses 2000, 2004, 2008, ........ 2036, so that the element with index i has the address 2000
+ i× 4.[hereα is base address whose value is 2000 and sizeof (int) is4]
For i=0,1,2… (size of int is 4 bytes(32bit machine))
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.
Dept. of CS&E,JIT-DVG 6
DATASTRUCTURE AND APPLICATIONS
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];
}
4. Insert item at the specified position
A[pos] = elem;
5. Update number of elements in the array
n=n+1;
6. Stop
1.5.3 Deletion
Deleting refers to the operation of removing one element from the array A with specified position.
Dept. of CS&E,JIT-DVG 7
DATASTRUCTURE AND APPLICATIONS
Algorithm:
1. Start
2. Read pos.
3. Move the elements towards left
for(i=pos ; i< n-1; i++)
{
A[i] = A[i+1];
}
4. Display deleted element at the specified position
elem = a[pos];
5. Decrement the number of elements in the array
n=n-1;
6. Stop
Dept. of CS&E,JIT-DVG 8
DATASTRUCTURE AND APPLICATIONS
The size used during declaration of the array is useful to reserve the specified memory locations.
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.
Dept. of CS&E,JIT-DVG 1
DATASTRUCTURE AND APPLICATIONS
0 1 2
0 11 22 33
1 44 55 66
Rows 2 77 88 99
3 10 20 30
2. Column major order: the elements are stored column by column one column at a time.
Ex: int a[4][3] = {{11,22,33},{44,55,66},{77,88,99}};
Dept. of CS&E,JIT-DVG 1
DATASTRUCTURE AND APPLICATIONS
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.
The above example declares a structure called person 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
Ex:
Struct student
{
char name[10]; 10 bytes
int roll_no; 4 bytes
float marks; 8 bytes
}; 22 bytes
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:
Dept. of CS&E,JIT-DVG 11
DATASTRUCTURE AND APPLICATIONS
Dept. of CS&E,JIT-DVG 12
DATASTRUCTURE AND APPLICATIONS
2. The complete definition of a structure is placed inside the definition of another structure.
Example:
typedefstruct
{
char name[10];
int age;
float salary;
struct
{
int month;
int day;
int year;
} date;
} humanBeing;
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;
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;
4.4 Unions
A union is a collection of data of similar data types or dissimilar data types. A union
declaration is similar to a structure, but the fields of a union must share their memory space. This
means that only one field of the union is "active" at any given time.
Syntax:
union tag-name
{
data_type member 1;
data_type member 2;
………………………
………………………
data_type member n;
};
Example:
unionstudent
{
char name[10];
intage;;
float salary;
Dept. of CS&E,JIT-DVG 14
DATASTRUCTURE AND APPLICATIONS
};
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.
C Structure C Union
keyword struct is used to define a structure keyword union is used to define a union
Structure allocates storage space for all its Union allocates one common storage space for
members separately. all its members. Union finds that which of its
member needs high storage space over other
members and allocates that much space.
Dept. of CS&E,JIT-DVG 15
DATASTRUCTURE AND APPLICATIONS
Structure occupies larger memory space. Union occupies lower memory space over
structure.
We can access all members of structure at a time. We can access only one member of union at a
time.
Address of each member will be in ascending Address is same for all union members.
order (different address).
Definition
“A pointer is a variable which contains the address of another variable as its value”.
Example:
1. int *ptr; // declares a pointer variable ptr of integer type.
2. float *temp; // declares a pointer variable temp of floating type.
Dept. of CS&E,JIT-DVG 16
DATASTRUCTURE AND APPLICATIONS
int a=3;
int *ptr;
ptr=&a;
ptr a
Memory layout:
65530 3
Address: 65530
„ptr = &a‟ copies the address of „a‟ to the pointer variable „ptr‟.
Example Program: Write a C program to print value and address of the variable using
pointers.
#include<stdio.h>
#include<conio.h>
void main () Output:
{ The address of a=65530 and value of a=20
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();
}
ptr1 a
Memory layout:
65530 20
Address: 65530
Dept. of CS&E,JIT-DVG 17
DATA STRUCTURES AND APPLICATIONS
Initializing a Pointer Variable
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
data_type *pointer_variable_name = address_of_variable;
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.
Static Allocation
If memory space is allocated for variables during compilation time, then it is called „Static
Memory allocation‟.
Size of memory space is „fixed‟; it can‟t be altered during execution time.
Example: int a [10];
During compilation, the compiler will allocate 10 memory locations for the array variable „a‟.
Inserting less than 10 elements leads to underutilization of allocated space and more than 10
elements cannot be inserted.
Dynamic Allocation
“Dynamic memory allocation is the process of allocating memory space during the
execution time (Run time).”
The various predefined memory management functions that are used to allocate or deallocate
memory are:
1. malloc( )
2. calloc( )
3. realloc( )
4. free( )
JIT, DAVANAGERE 1
DATA STRUCTURES AND APPLICATIONS
Syntax:
ptr = (data_type *) malloc (size);
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.
Syntax:
ptr = (data_type *) calloc (n,size);
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.
JIT, DAVANAGERE 2
DATA STRUCTURES AND APPLICATIONS
means, the size of the memory changes by extending or deleting the allocated memory.
When realloc() is able to do the resizing, it returns a pointer to the start of the new block and
when it is unable to do the resizing, the old block is unchanged and the function returns the value
NULL.
Syntax
ptr = (data_type *)realloc (ptr, new_size);
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”);
Ex:int *ptr;
ptr = (int *) malloc(100*sizeof(int));
free(ptr);
JIT, DAVANAGERE 3
DATA STRUCTURES AND APPLICATIONS
Difference between malloc() and calloc() Functions in C:
malloc() calloc()
It allocates only single block of memory. It allocates multiple blocks of memory.
int *ptr; int *ptr;
ptr = malloc( 20 * sizeof(int)); ptr = calloc( 20, 20 *sizeof(int) );
For the above, 20*4 bytes of memory are For the above, 20blocks of memory will be
allocated in one block.Total = 80 bytes allocated and each contains20*4 bytes of
memory.Total = 1600 bytes.
malloc() doesn‟t initializes the allocated calloc() initializes the allocated memory to
memory. It contains garbage values zero.
ASSIGNMENT QUESTIONS
JIT, DAVANAGERE 4
DATA STRUCTURES AND APPLICATIONS
JIT, DAVANAGERE