0% found this document useful (0 votes)
11 views23 pages

dsu_ 1lesson

22319 chapter 1

Uploaded by

safinafpathan123
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)
11 views23 pages

dsu_ 1lesson

22319 chapter 1

Uploaded by

safinafpathan123
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/ 23

KScheme

Sem.II

NewSyllabus
MSBTE

Asper newrevised K
Scheme w.e.f. academicyear 2024-2025
DATA STRUCTURE
USING C
(Code : 313301)
Second Year Diploma - Semester III- Computer Engineering
Information Technology / Cloud Computing &Big Data /
CT/CSE/ CHM/CS &IT [BD/CM/CO/CW/HA/IF/IH]
Dilip Kumar Sultania
TM
Includes :
"Solved previous MSBTE Question Papers.
"Lab Assignments.
Tech Knowledge
PubliC ations
Data Structure
Using C'
(Code : 313301)

SECOND YEAR DIPLOMA

Maharashtra State Board of Technical Education (MSBTE)

Semester III - Computer Engineering /Information Technology / Cloud Computing &


Big Data /CT / CSE/ CHM / CS &IT (BD/CM/CO/Cw/HA/IF/IH)

Strictly as per new revised KScheme w.e.f. academic year 2024-2025

DilipKumar Sultania
B.Tech.(hons.) Computer Science and Engineering
LI.T., Kharagpur

|SPECIMEN COPY FOR


REVIEW&
RECOMMENDATION
937031 4831

TechKnowledge
PubI icati ons
MDO97A Price 355/
LABORATORYLEARNINGOUTCOME
EXPERIENCES
TUTORIAL
PRACTICAL/ Numberof Relevant
ALIGNED TItles COs
AND Titles/Tutorial
Practlcal
hrs,
Experiment / CO1
Laboratory 4
Create,
Sr.
Operations on Array :
No following
program to perform CO2
Write a C
given Array of
1
Insert, Delete, Display.
from the
particular data
a
Program toSearch C02
2 Write a'C Method. 2
LinearSearch given Array of
numbers using: from the
particular data
Program toSearch a
3 Write a 'C' Method. 2
C02
LinearSearch given Array of
Strings using
particular data from the
program to Search a
4 Write a 'C' Method. C02
BinarySearch 2
numbers using given Array of
particular data from the
to Search a
Write a C Program
Search Method. CO2
Strings using Binary using Bubble Sort
2
Array of numbers
C Program to Sort an
6 Write a
Method. 2 CO2
Method.
Array of Strings using Bubble Sort
Sort an
7 Write aC Program to Sort 2 CO2
Array of numbers using Selection
to Sort an
8 Write a 'C Program
Method. 2 C02
Selection Sort
Program to Sort an Array of Strings using
9 Write a 'C
Method.
2 C02
Insertion Sort
Program to Sort an Array of numbers using
10 Write a C
Method.
Sort 2 CO2
Array of Strings using Insertion
11 Write a 'C Program to Sort an
Method.
CO3
List with Operations 2
12 Write a 'C' Program to Implement Singly Linked
() Insert at beginning, (i)Search, (ii) Display
C03
13 Write a C Program to Implement Singly Linked List with Operations : 2

() Insert at end, (ii) Insert After, (iii) Delete (iv) Display

14 2 C03
Write a CProgram to Create Two Polynomials using a Linked List.
15 Write a 'C Program to add Two Polynomials using a Linked List. 2 C03

16 Write a 'C' Program to perform PUSH and POP Operations on Stack using 2 C04
an Array.
17 Write a 'C' Program toperform PUSH and POP Operations on a Stack using 2 C04
a Linked List.
Sr. Laboratory Experiment /Practical Titles/ Tutorial Titles Number of
No Relevant
hrs. COs
18 Write a C program to perform
recursion. multiplication of two numbers using CO4

Write a'C program to print given


stringin reverse using recursion. C04
20 Write a C progtam to create a Singly
Linked List and traverse in reverse 4 C03
order using recursion.
C04
21 Write a C Program to perform INSERT and
Queue using an Array. DELETE Operations on Linear 2 COS

22 Write a 'C Program to perform INSERT and


Queue using a Linked List. DELETE operations on Linear 2 CO5

23 Write a C Program to perform


INSERT and DELETE operations on CO5
Circular Queue using an Array.
24 Write a 'C Program to performn INSERT and
DELETE operations on 2 CO5
Circular Queue using a Linked List.
25 Write a 'C Program to Create a Priority Queue using a Linked List. 4 CO5
26 Write a 'C Program to Implement BST (Binary Search Tree) and
in In-Order.
Traverse 2 CO6

27 Write a 'C Program to Traverse BST in Preorder, and Post-Order. 2 C06


Table of Content
1
Data Structure Using C
Introduction to Algorithm. .1-8
1.6
Unit -I
1.7 Different Approaches for Designing an
.1-10
Chapter1: Introductlon to Data Structures 1-1to1-14 Algorithm.

1.7.1 Top-down Approach..n .1-10

Syllabus Bottom-up Approach. .1-11


Structure, 1.7.2
1.1 Introduction : Concept and Need of Data
Definition, Abstract Data Type
1.8 Complexity in Terms of Time and Space. 1-11
Structures
1.2 Types of Data Structures: () Linear Data
1.8.1 Algorithm Analysis. .1-11
() Non-Linear Data Structures

|13
Operations on Data Structures: (0) Traversing Measuring the Running Time ofa Program
1.8.2
(ü) Insertion (ü) Deletion .1-12
(Time Complexity).
1.1 Data Representation....n 1-1 Measurement of Growth Rate (Asymptotic
1.8.3

Growth Rate). 1-12


Data... 1-1
1.1.1

.1-1 1.8.3(A) Asymptotic Consideration... .1-12


1.1.2 Data Types.
.1-2
1.8.3(B) Constant Factor in Complexity Measure....1-13
1.1.3 Data Types in C.......

1-3 1.9 The Notation 0: (Pronounced as big-oh),


1.1.4 User-defined Type.
(o(n) is Pronounced as big-oh of n² )]..1-13
1.1.5 Derived Data Types 1-3

Unit - II
1.1.6 Structure. 1-3

1.1,7 Union. 1-4 2-1 to 2-40


Chapter 2 : Searching and Sorting
1.2 Abstract Data Types (ADT) 1-4
Syllabus
1.3 Concept of Data Structures.. .1-5 2.1 Searching:Searching for an item in a data set using
the following methods: (0 Linear Search (i) Binary
1.3.1 Need of Data Structure..... .1-5 Search

1.3.2 Linear and Non-Linear Data Structures.....1-6 |2.2 Sorting : Sorting of data set in an order using the
following methods :0) Bubble Sort (i) Selection Sort
1.3.2(A) Difference between Linear and Non-linear Data (ii) Insertion Sort (iv) Quick Sort (v) Merge Sort.
Structure. 1-7
2-1
2.1 Searching.
1.4 Classification of Data Structure........ 1-7
2.1.1 Sequential Search (Linear Search). .2-1

1.4.1 Primitive and Non-Primitive 1-7


2.1.2 Sequential Search on a Sorted Array .2-3

1.5 Operations on Data Structures 1-8


.2-3
2.1.3 Binary Search..
TechKaoiedge
Using C Tabie of Contents
Data Structure

nforence between Linear Search and Binary 2.7,4 Advantages and Disadvantages of Merge Sort..
2.1.4
Search .2-11 .2-40

2.2 Sorting .2-11


Unit - IIi
Sort Stability .2-12
2.2.1
Chapter 3; Linked List 3-1to 3-35
2.2.2
Sort Efficiency .2-12

Passes .2-13
Syllabus
2.23
3.1 Difference between Static and Dynamic Mernory
Bubble Sort. .2-13
2.3 Allocation.
Selection Sort. 3.2 Introduction to Linked List, Terminologies : Node,
2.4 .2-16
Address, Pointer, Information field / Data field, Next
2.5 Insertion Sort.... .2-18 pointer, Null Pointer, Empty List.

Sorting an Array of Strings using Insertion Sort 3.3 Type of Lists : Linear List, Circular List, Representation
2.5.1
of Doubly Linked List.
.2-21
3.4 Operations on a Singly Linked List :Creating a Linked
2.5.2 Sorting an Array of Records on the given Key List, Inserting a new node in a Linked List, Deleting a
using Insertion Sort. .2-22
node from a Linked List, Searching a key in Linked
List, Traversing a Singly Linked List.
2.6 Quick Sort. ..2-27 3.5 Applications of Linked List.

2.6.1 Picking a Pivot.. s..2-27


3.1 Representation and Implementation of Singly
Linked Lists......... .3-1
2.6.2 Partitioning. ..2-27

2.6.3 Running Time of Quick Sort.... .2-32 3.1.1 Comparison between Array and Linked Lists....
3-1
2.6.3(A) Worst-case Analysis. ...2-32
3.1.2 Representation ... .3-2
2.6.3(B) Best-case Analysis. .2-32
3.1.3 Implementation .3-2
2.6.3(C) Average-case Analysis... .2-32
3.1.4 Types of Linked List.. ..3-4

2.6.4 Advantages and Disadvantages of Quick Sort


3.1.4(A) Singly Linked List.
.....2-33
3.1.4(B) Doubly Linked List... 3-4
2.7 Two-Way Merge Sort. .2-33
3.1.4(C) ACircular Linked List... ..3-4
2.7.1 .2-35
Merging.m 3.1.4(D) Advantages of Circular Link List over Linear
2.7.2 Analysis of Merge Sort.. ..2-38 Link List. ..3-5

2.7.3 .2-38 3.1.4(E) Difference between Linear Linked List and


Non-Recursive Merge Sort.
Circular Linked List. ..3-6

Tech kaewledgi
Data Structure Using C 3
Table of Content.
3.2 Basic Linked List Operations. 3-6 3.5.1 Polynomials as Linked Lists
3-26,
3.21 Creating a Linked List. 3-6 3.5.2 Addition of Two Polynomials..
327
32.2 Traversing aLinked List. 3-7
Unit - IV
3.2.3 Counting Number of Nodes in a Linked List
through Count Function "..3-8 Chapter 4: Stack 4-1 to 4-44
3.2.4 Printing a List through Print Function...3-9 Syllabus
3.2.5 Inserting an Item.. .3-9 |4.1 Introduction to Stack: Definition, Stack as an ADT
Operations on Stack-(Push, Pop), Stack Operatione
3.2.5(A) inserting an Item at the End of a Linked List..
Conditions Stack Full/ Stack Overfiow, Steck
.3-10
Empty/Stack Underflow.
3.2.5(B) Inserting a Data 'x at a Given Location "LOC' in |4.2 Stack Implementation using Array and representation
a Linked List, Referenced by 'Head'. .3-10 using Linked List.

3.2.5(C) Inserting an Element in a Priority Linked List... |4.3 Applications of Stack : Reversing a List, Polish
Notations, Conversion of Infix to Postfix Expressior.
.3-11
Evaluation of Postfix Expression.
3.2.6 Deleting an Item. .3-12 |44 Recursion: Definition and Applications.
3.2.6(A) Deletion of the Last Node of a Linked List..3-13 4.1 Introduction to Stack.
32.6(B) Deletion of a Node at Location 'LOC" from a 4.2 Stack as an ADT.
Linked List. .3-13 4.3 Operations on StackS 4-2
4.4 Array Representation. 4-4
3.2.6(C) Delete a Linked List, Referenced by the Pointer
Head 3-14
4.4.1 'C Functions for Primitive Operations on a
Stack.. 4-4
3.2.7 Concatenation of TwoLinked Lists .....3-15 4.5 Program Showing Stack Operations ...4-5
3.2.8 Inversion of Linked List. 4.5.1 Operations on Stack Considering Overflow and
.3-15
Underflow [Array Implementation.4-7
3.2.9 Searching a Data 'x' in aLinked List, 4.5.2 Reversing a List.... 4-8

Referenced by the Pointer Head .3-16 4.6 Linked Representation of a Stack. 4.

3.2.10 Searching an Element x in aSorted Linked List 4.6.1 Functions for Stack Operations. 4-10
s..... 3-17 4.7 Applications of Stack. 4-12

3.2.11 4.7.1 Expression Representation. 4-13


Handling of Records through Linked List...3-18
4.7.2 Evaluation of aPostfix Expression usinga
3.2.12 Head Node in Linked List .3-18 Stack. 4-14

3.3 Circular Linked List 4.7.3 Evaluation of a Prefix Expression 4-18


.3-19
4.7.4 Conversion of an Expression from Infix to
3.4 Comparison of Linked List and Array.....2.6 ..4-20
Postfix.
3.5 Applications of Linked Lists............. .3-26
Tech Kaowle[ge
Using C Table of Contents
Data Structure

4.7.5 Conversion of an Expression from Infix to 5.3 Linked Representation of aQueue.......5.9


Prefix.... 4-29
5.3.1 Comparison between Array Representation
4.8 Expression Conversion (A Fast Method)...4-32
and the Linked Representation of a ueue
Infix to Postfix. 4-32
48.1 5-10
Inix to Prefix .4-32
4.8.2
5.3.2 Operations on Queue Implemented using
4.8.3 Postfix to Prefix. 4-33
Linked Structure. .5-10
Prefix to Infix 4-35
4.34
5.4 Types of Queue. 5-15
49
Introduction to Recursion 4-39
5.4.1 Circular Queue (Array). 5-15
4.9.1 Converting a Recursive Function to an
Equivalent C-Function. .4-39
5.4.2 Implementation ofa Circular Movement inside
491/A) Finding Factorialof an Integer Number..4-39 a Linear Array. 5-16

4.9.2 Tower of Hanoi Problem .4-41


5.5 Priority Queue. .5-20
4.9.3 Stack in Recursive Function........ -43
5.5.1 Implementation of Priority Queues. .5-20
Unit - V 5-24
5.6 Applications of Queue
5.6.1 Josephus Problem .5-24
Chapter 5: Queue 5-1 to 5-26
5.6.2 Job Scheduling. .5-25
Syllabus
15.1 Introduction to Queue : Queue as an ADT, Queue
5.6.3 Queue Simulation. 5-26

representation ir memory using Array and


representation using a Linked List. Unit VI
5.2 Types of Queues : Linear Queue, Circular Queue,
Chapter 6: Tree 6-1 to 6-39
Concept of Priority Queue, Double-Ended Queue.
5.3 Queue Operations : INSERT, DELETE Queue Syllabus
Operation Conditions:Queue Full, Queue Empty. 6.1 Introduction to Trees Terminologies: Tree, Degree of
54 Applications of Queue. a Node, Degree of aTree, Level of a node, Leaf Node,

5-1
Depth / Height of a Tree, In-Degree and Out-Degree,
5.1 Introduction. Path, Ancestor and Descendant Nodes.
5.1.1 Array Representation and Implementation of 6.2 Tree Types and Traversal methods, Types of Trees
Queues... 5-1
General Tree, Binary Tree, Binary Search Tree (BST).
5.1.2 Comparison between STACK and QUEUE....5-2 Binary Tree Traversal: In-Order Traversal, Preorder
5.1.3 Traversal, Post-Order Traversal.
Queue Overflow and Underflow.............5-2
6.3 Expression Tree, Heap.
5.2 Operations on Queue (Implemented using
Array) 5-4 6.1 Introduction to Trees bs.. 6-l

5.2.1 Queue as an ADT 5-8 6.1.1 Basic Terms .6-1

Techknowtedge
Data Structure Using C Table of Contents
6.2 Binary Tree. 6-3 6.7 Binary Search Tree (BST).
.6-17
6.2.1 Representation of a Binary Tree using an Array 6.7.1 Definition ...
.6-17
6-3
6.7.2 Operations on a Binary Search Tree....6-1
6.2.2 Linked Representation of aBinary Tree...6-4
6.7.2(A) Initialize Operation.. 6-18
6.3 General Tree. ..6-5
6.7.2(B) Find Operation... ..6-18
6.3.1 Node Declaration for a Tree. .6-5
6.7.2(c) Makeempty Operation .6-18
6.3.1(A) Comparison between General Tree and Binary
Tree .6-7
6.7.2(D) Insert Operation. 6-18

6.4
6.7.2(E) Examples on Creation of a BST. .6-19
Types of Binary Tree. .6-7
6.7.2(F) Delete Operation... 6-25
6.4.1 Full Binary Tree.... .6-7

6.4.2
6.7.2(G) Create .6-27
Complete Binary Tree. .6-7
6.7.2(H) FindMin .6-27
6.4.3 Skewed Binary Tree... 6-8
6.7.2(1) FindMax.. ...6-28
6.4.4 Strictly Binary Tree........ 6-8
6.7.3 Program for Various Operations on BST...6-28
6.4.5 Extended Binary Tree (2-Tree) 6-8
6.8 Application of Trees. .6-30
6.5 Binary Tree Traversal.. .6-8

6.5.1
6.8.1 Expression Trees. .6-30
Preorder Traversal (Recursive)......6-9
6.8.2 Conversion of an Expression into Binary Tree
6.5.2 Inorder Traversal (Recursive),....6-10
sedesebepsstspeb!.6-31
6.5.3 Postorder Traversal (Recursive)J ...6-11
List of Practicals.... .L-1 to L-31
6.6 Tree Traversal Examples. ..6-11
Introduction to Data Structures

Syllabus
troduction :Concept and Need of Data Structure, Definition, Abstract Data Type
. Tvoes of Data Structures: (i) Linear Data Structures (ii) Non-Linear Data Structures

13 Operations on Data Structures () Traversing (0) Insertion (ii) Deletion

1.1 Data Representation Composite data


data and hence
Data is a collection of numbers, alphabets and It isa composition of several atomic
it can be further divided into atomic data.
Svmbols combined to represent information. Acomputer
For example, date of birth (say 15/3/1984) can be
takes raw data as input and after processing of data it
separated intothree atomic values. First one gives
nroduces refined data as output. We might say that the day of the month, second one gives the month
data.
Computer science is the study of and the last one is the year.
Composite data
Binary system of representation is used in Date of birth
computer.
An integer number is represented by its binary
Month Year
equivalent Day

A negative number is represented using 2's


complement representation Atomio data
Fig. 1.1.1
character is represented using its ASCIIcode.
A
A real number is represented using IEEE 1.1.2 Data Types
representation format. A data type is a term which refers to the kind of

1.1.1 Data data that variables may hold in a programming


language.
Data is a collection of numbers, alphabets and Ex. : int x;[x can hold, integer type data)
symbols combined to represent information. Acomputer Every programming language has a method for
takes raw data as input and after processing of data it declaring a set of variable of a particular type. A
produces refined data as output. We might say that value stored in a variable can not be interpreted
computer science is the study of data. properly without knowing its type. A byte of
Atomicdata information stored in computer memory may
represent an integer value, a character value, a BCD
They are non-decomposible entity. For example, an (Binary Coded Decimal) value or a Boolean value.
integer value 523 or a character value A' cannot be Therefore, it is necessary that the value stored in
further divided. If we further divide the value 523 in memory must be treated as of a particular type and
three digíts '5', "2' and'3' then the meaning may be lost. interpreted accordingly.
Data Structure Using C 1-2 Introduction to Data Structura.

1L1.3 Data Types in 'C


allows variables to narme data of h.
In every programming language there is set of built-in data types. Language
Ever.
Vpe. It also allows a set of operations (through operators like +,-/% etc) for manipulation of these values.
programming language has its own representation for primitive data types.

Data types in 'C'

Prímary or built in type Void User defined Derived data types

Integer Charaoter Real Pointer Typédef Enumerator Array Structure Union

Signed Urnaigned

Normal Long Pointer to Pointer to Pointer to Pointer to


Signed Uneigned float Double Double
Integer Character Real Derived type

Short Normal Long Short Normal Long

Fig. 1.1.2: Data types in 'C


Table 1.1.1:Size and range of data types on a 16-bit m/e

Type Size (bits) Range Representation

Char or signed char 8 - 128 to 127 2's complement ASCII

Unsigned char 8 0 to 255 Binary ASCII

int or signed int 16 -32,768 to 32,767 2's complement

Unsigned int 16 0 to 65535 Binary

Short int or signed short int - 128 to 127 2's complement

Unsigned short int 0 to 255 Binary

Long int or signed long int 32 - 2, 147,483, 648 2's complement


to 2, 147,483,647

Unsigned long int 32 0to 4, 294,967, 295 Binary


Float 32 3.4E -38 to 3.4E + 38 IEEE

Double 64 1.7E- 308 to 1.7E + 308 IEEE

Long double 3.4E -4932 to 1.1E+ 4932 IEEE

TechKaowledge
Using C 1-3 Introduction to Data Structures
Data Structure

Program 1.1.1: Program to accept and display 'int' and 1.1.5 Derived Data Type
'char' type of data. W-15
Q. Explain the term: Derived data type.
#include <stdio.h>
elements is stored in
# include <conio.h> Array :Agroup of similar

void main () contiguous memory.


Ex. int a[6]: /* defining an array of size 6 */
int x;
a[0] a[1] a[2] a[3] a[4) a(5]
char y;
of six elements.
Drintf("\n enter an integer value:"); int a<6] defines an integer array
memory
These elements are stored in contiguous
scanf("%d", &x); as "a[i]"
locations. An element of the array is accessed
printf("n entered value =%d x;
where a is name of the array and i is index.
Drintf("\n enter acharacter value :");
scanf("%C", &y): 1.1.6 Structure

Drintf("n entered value = %(" y): non-homogeneous elements.


It allows, one to group
attributes of an entity
getch; It becomes necessary to group all
single cell. Without
or properties of an object in a
handle a
structure, it becomes extremely difficult to
1,1.4 User-defined Type complex data structure.
"type definition" allows user to define an identifier For example
that willrepresent anexisting data type.
struct student
For example :typedef float marks;
After above declaration, marks can be used for float.
char name [35];
marks phy,che, math; int rollno;
Here, marks is another name for float. Marks can be char address [120};
used to declare variables of the type float. This int gender;
approach, enhances readability of a program. };
Another user-defined data type is enumerated Struct student S1: S2:

data type. Elements of a structure type variable can be


An example : accessed through dot () operator.
enum day (Mon, Tue, Wed, Thu, Fri, Sat, Sun); Sl.name; name of students */
S1.rollno;
enum day today ;
Variable today, which is declared of enum day type S1.address;
can be assigned a value from the set (Mon, Tue, S1.gender,
Wed, Thu, Fri, Sat, Sun). Array is used for storing of homogeneous elements,

today =Thu; *A valid statement */ structure can be used for storing of non-homogeneous
elements.
if (today == Mon) /*A valid statement */

today =Fri; *A valid statement */


Tech Knowedgé
Introduction to Data
Data Structure Using C

1.1,7 Union
1-4

Lvol 0
Man
Structures
Progrom

Unions are a concept borrowed from structures and


therefore follow the same syntax as structures.
Leve 1
However, there is major distinction between them
in terms of storage. In structures, each member has íts
Level 2 2
Own storage location, whereas all the members of a
union share the same memory locations.
Fig. 1.2.1: Hlerarchical organized program
Example :
When the program is hierarchical organized
Union item shown in the Fig. 1.2.1, then the "main progra
int m; utilizes services of the functions appearing at leval
loat x 1. Similarly, functions written at level 1 utilize
services of functions written at level 2.
char c:
Main program uses the services at the next leval
item cd ;
functions without knowing their implementation
Storage of 4 bytes details. Thus a level of abstraction is created. When
2000 2001 2002 2003 an abstraction is created at any level, our concern is
limited to "what it can do" and not "how it is done"
Abstraction in case of data

Abstraction for primitive types (char, int, float) is


provided by the compiler. For example, we use
integer type data and also, perform various
operations on them without knowing:
Fig. 1.1.3: Sharing of storage locations by the
members of union (1) Representation
(2) How various operations are performed on them.
To access a union member, we can use the same
syntax that we use for structure members. Example :
ie. item_cd.m int x,y, zi
item_cd.x X=-13;
Constant -13 is converted to 2's complement and
item_cd.c
then stored in x. Representation is handled by the
1.2 Abstract Data Types (ADT) compiler.
X=y+z;
Q. Describe abstract data type. S-22, W-22
Meaning of the operation + is defined by the
The concept at abstraction is commonly found in compiler and its implementation details remain
computer science. Abig program is never written as hidden from the user.
amonolithic piece of program, instead it is broken Implementation details (representation) and how
down in smaller modules (may be called a function various operations are implemented remain hidden
or procedure) and each module is developed from the user. User is only concerned about, how to
independently. use these operations.
Tech Kaowiedge
Data Structure Using C 1-5 Introduction to Data Structures

Ohiects such as lists, sets and graphs along with 4 Delete(L, P): Delete the element at position P
associated operattons, can be viewed as abstract of the list L.

data type. Integer, char, real are primitive data 5 MAKENULL(L): Creates an emptyiist L.
unes and there are set of operations associated 6 PrintList(L): Print the elements of L in the
with them. For the 'set' ADT (Abstract Data Type), order ofoccurrence.

We might have operations like union, intersection, 1.3 Concept of Data Structures
size and complement. Once the data type set is
Q. Define data struoture. Enlist any two types of non
defined (representation and associated functions)
linear data structure. W-15
then the ADT set can be used in any application
W-16
program. Q. Define data structure.

The abstract data type "List" The data structure is concerned with the following

A
list is a sequence of0 or more elements of agiven things :
type (element type could be integer, float etc.). Such 1 Organization of data
a list is often represented as: 2 Associativity among data elements
3 Accessing methods
n= Number of elements in the list 4. Operations on data
a = i element of the list 5 Processing alternatives for data.
When n =0, the list is empty having no element.
While representing data, relationship between
Each element other than a has a predecessor individual elements of the data should. be
Each element, other than a, has a successor. considered. The data structure deals with

In order to form an ADT from the mathematical representation of data considering not only the
notation of a list, we must represent the list and elements stored but also their relationship to each
define a set of operations on objects of type List. other.

Representation of a list For writing an efficient program, a proper data


structure should be selected.
A
List can be represented in C using a structure.
A proper data structure should be selected so
typedef struct List that the relationship between data elements
{ int datal[50]: can be expressed.
int n; Processing and accessing of data should be
} List; efficient.

AList of maximum of 50 integer type elements A data structure can also be defined as an instance
of ADT. A data structure is formally defined to be a
n is the actual number of elements in the List.
triplet (D, F, A)
A
set of representative operations on a list where, D
stands for a set of domains
1. Insert(L,X, P): Insert Xat position Pin list L. F stands for a set of operations
2 Locate(X, L): This function returns the position Astands for a set of axioms.
of element X on list L.
1.3.1 Need of Data Structure
3 Retrieve(L, P): This function returns the element
at position P on list L. Q. State the need of data structure. S-16

TechKnouledge
Introductionto Data
Data Structure Using C 1-6Representation of linear data structures throug Structure
There is a close connection between the
structuring linked structure
of data and the synthesis of algorithm. For each
data
item, there are number of operations. Data should
be represented in a way that makes efficient
A Ast of
implementation of operation. Elerments
Addrogs of the ext
plement

If a linear
data is represented using linked Top
organization then modification is less time
Stack
consuming whereas accessing a large list becomes
inefficient. In sequential organization, accessing is Front
Rçat
efficient but modifications are costly.
Cuoue
1.3.2 Linear and Non-Linear Data Structures
Q. Explain linear and non-linear data 2, Non-linear
structures.
W-15, S-23, W-23 relation.
All one-many, many-one or many-Many
Q. Define linear data structure and non-linear data
are handled through non-linear data structure
structure. | W-18, S-22 Every data element can have a number
predecessors as well as successors. Tree graphs ant
Types of Data Structure
tables are examples of non-linear data structures.
1. Linear

2. Non- Linear

Fig. 1.3.1 :Types of Data Structure


Tree Graph
1. Linear
(a) (b)
Elements are arranged in aLinear fashion (one 5 91
dimension). All one-one relation can be handled 13
2
through Linear data structures. Lists, stacks and
6 11
queues are examples of linear data structure.
Representation of linear data structures inm an array (c) Table
A tist of
Fig. 1.3.2: Non- linear data structures
array
elernents root

th
0element (n-1) eBement

Top
9
Stack 23

Front Rsar

Fig. 1.3.3(a) : Representation of the binary tree


Queue 1 23 through linked structure

Tech Kaouiedg!
Data Structure Using C . no
osflernerts
1-7 Introduction to Data Structures

- r oe
o ttorrent
root

toot
St. Linear Non-Linear
child
of

o f

c h i l d
No.
elements
left

rigta
3 Data elements are Data are

arranged in a linear arrarnged in anon-linear


(hierarchical) order.
ZT6LÚ9T2|3 order.

(b) Representation of1the binary tree through an array 4 Memory is not Memory is utilized in an
Fia. 1.3.3:Representation of tree of Fig. 1.3.2(a) utilized in an efficient way.
efficient way.
1.3.2(A) Difference between Linear and Non
linear Data Structure 1.4 Classification of Data Structure
O. Differentiate between lineár and non-linear data W-16, W-19
Q. Give classification of data structure.
structure. (any four points). W-22
a. Descirbe classification of data structure with example
Sr. Linear Non-Linear of each. W-17, S-18
No.
Data structures are normally divided into two
1 Elements are Elements are
categories:
sequentialy hierarchically
connected connected. 1 Primitive data structure

2 Easy to implement. Difficult to implement. 2. Non - Primitive data structure (derived)

Classification of data structure is shown in Fig, 1.4.1.


Data Structure

Primitive Non-Primitive(Derived)

integer Character Float Pointer Arrays Lists Structure Files

Linear Non-Linear

Stack Queue Tree Graph


Fig. 1.4.1: Classification of data structure
1.4.1 Primitive and Non-Primitive
Q. Define the terms :
(1) Primitive data structure (2) Non primitive data structure. S-15

Primitive

The integers, reals,logical data, character data, pointers and reference are primitive data structures. These data
types are available in most programming languages as built in type. Data objects of primitive data types can be
operated upon by machine level instructions.

Tech Knoaledqë
Structures
Introductionto
Data
Data Structure Using 1-8 structure,
data
datainthe
Non-primitive 3. Inserting is adding a new structure.
from the data
Deleting is removingaa data
These data structures are derived from prímitive 4
somelogicalorder.
data in
data structures. A set of homogeneous and Sorting is arranging of
data structures.
5
heterogeneous data elements are stored together. combining oftwo similar
6 Mergingis
Examples of Non-primitive data structures : Introduction to Algorithm
1.6
Array, structure, union, linked-list, stack, queue, S-16, S-18

tree, graph. Q. Define an algorithm. W-17, W-18


algorithm.
Some of the most commonly used operations that a. Definethe term around
Science revolves
can be performed on data structures are shown in The field of Computer
problems for
programs for several
Fig. 1.4.2. writing of consists of data
program
Operation various domains. A
structuresand algorithms.
solve a
of steps required to
Destructio Update Selection Search Sort An algorithm is a set performed on asample
GRata problem. These steps are
instance of the problem. Thus
Fig. 1.4.2: Data structure operations data representing an
input data (from input
an algorithm maps a set of
output domain)
1.5 Operations on Data Structures domain) toa set of output data (in
An algorithm
through a sequence of operations.
Q. Describe any four
operations on data structure. must have the following properties :
S-19, W-19
S-15, W-15, S-16, W-17, S-18, Properties of Algorithm
can be performed on
a. Write any four operations th¡t
S-23, W-23
data structure. (1) Input

on a data structure.
Many operations are performed (2) Output
structure are:
Typicaloperations on a data (3) Finiteness
Operation of Data
Structure
(4) Definiteness
1. Traversing
(5) Efectiveness
2. Searching
Fig. 1.6.1 : Properties of Algorithm
3 insertion
(zero or
(1) Input: Input data, supplied externally
4, DéletiGn
more).
5. Sorting (2) Output : Result of the program.
algorithm terminates
6. Merging (3) Finiteness : In every case,
after a finite number of steps.
Fig. 1.5.1:Opeation of Data Structure should be clear and
(4) Definiteness: The steps
1 Traversing a data structure is accessing each data unambiguous.
should be written
and accessing only once. (5) Effectlveness : An algorithm
should be feasible to
2. Searching is finding the location of a data in within using basic instructions. It
the given data structure. convert the algorithm in a computer program.
TechKnowledge
Using C
Data Structure 1-9
Take the problem of finding the GCD (Greatest Introduction to Data Structures
Common Divisor) of two positive integers an Table 1.6.1
example. Steps Value of the
Inputs to the algorithm are two positive integers. performed varlables
Output is a positive integer which is GCD of two
positive integers given as input. Step 1 15
input data supplied
1Number
Algorithm
externally
tor finding
Step 2 15 1
Number GOD GCD
Step 3 15 9 6 1

Step 4 9 6 1

Alaorithm shoukd have thesA propertjes Step 5 6 1

Step 6 9 6 6 1

Finiteness Definiteness Etectiveness Step 2 3 1

Fig. 1.6.2 Step 3 6 3 1

The algorithm is described as a series of steps of Step 4 6 6 3 1


basic operations. These steps must be performed in Step 5 6 3 3 1
a sequence. Each step of the algorithm is labeled.
Step 6 6 3 3 1
Step 1: Read two positive integers and store them in
Step 2 3 2
xand y.
Step 3 6 3 2
Step 2: Divide xby y. Let the remainder ber and the
quotient be q. Step 7 Print the output (GCD) as 3.
Step 3: Ifr is zero then go to step 7. Algorithm terminates after a finite number of steps.
Step 4: Assign yto x. It is easy to prove that the algorithm will terminate
Step 5: Assign r to y. for any two given integer numbers. Thus the above

Step 6: goto step 2.


algorithm satisfies the finiteness property of the
algorithm.
Step 7: Print y(the required GCD)
Every programming language has input statement,
Step 8: stop. output statement, assignment statement,
The steps mentioned in the above algorithm are conditional branching statement, unconditional
simple and unambiguous. Anybody, carrying out branching statement and hence the above algorithm
these steps will clearly know what to do in each can easily be converted to a program. Thus the
step. Hence, the above algorithm satisfies the above algorithm satisfies the effectiveness
definiteness property of an algorithm. property of the algorithm.
Table 1.6.1 depicts step-wise execution of the above An algorithm can be described in many ways. A
algorithm on two input numbers 15 and 9. language like English can be used but it should be
free from any ambiguity. Flowcharts, consisting of
graphical symbols like :
Techknouuledge
Data Structure Using C 1- 10 Introduction to Data Structurec

Step 5 read x
Table 1.6.2: Symbols used in flowcharts
Step 6 Assign SUM +XTo SUM
Symbol Purpose
Step 7 : Assign I+ 1 to !
Terninal SymtoB
(Start/ Stop) Step 8 Go to step 4
Step9 : Print SUM
Assignment Statements,
express0on eto. Step 10: Stop

Read /Print 1.7 Different Approaches for Designing


an Algorithm
Decision making Q. Describe different approaches to design an algorithm.
s-15. S-17, W-17, S-18
Connector Q. Compare Top-down approach v/s Bottom-up
approach (any four points]. W-15,W-16
Flow indication
Design of an algorithm is an important issue. There
are several approaches for designing an algorithm. These
Ex. 1.6.1: Wite an algorithm for adding 10 numbers. approaches include:

Soln.: FIlowchart Different Approaches


for Designing Aigoritm
Start
1. Top-down Approach
N= 10, sUM =0 2. Bottom-up Approach
I=1

Fig. 1.7.1: Different approaches


for Designing Algorithm
No
I<=N Print SUM/ 1.7.1 Top-down Approach
Yes
Stop
One has to write a program to solve a specific task.
Asingle procedure is never written tO solve a large
Read X
task.

SUM= SUM +X Aprogrammer tries to partition the solution into


=1+1 subtasks. Each subtask is similarly decomposed
until all tasks are expressed within a programming
Fig. Ex. 1.6.1: Flowchart for adding 10 numbers
language.
Algorithm as a series as steps : Thus the top-down method of design is based on
Assign 10 to N decomposing a large problem into sub-problems
Step 1
Assign 0 to SUM and keep repeating this process till the resulting
Step 2
sub-probiems are so simple that their solutions can
Step 3 i Assign 1 to l be expressed in a few lines of a programming
Step 4 if (l>N) go to step 9 language.
Tech Kaowiedge
1-11 Introduction to Data Structures
StrUcture UsingC
Data
Bottom-upApproach and hence the goal (ii) should be given more
1.7.2
is reverse of top-down approach. weightage.
This approach problem are first solved
different parts of the Analyzing a program should quantify the
Here. the requirement of computing resources during
programminglanguage and then these pieces of
using a combined into a complete program. execution. Most ímportant of these resources are
programsare
computer time and memory.
and bottom-up approach
ExampleofTop-down Analysis of algorithms focuses on computation of
down, we travel from root node to Leaf
ln top space and time complexity. Space requirement
bottom - down approach, we follow from leaf either
node. In means the space required to store input data
node.
nodeto root static or dynamic.
Root
handle
Space required on top of the system stack to
recursion/function Call should also be considered.
Computing time, an algorithm might require for its
Too down Bottom-up
approach
approach
execution, would normally dependon the size of the
+ Loaf input.
#include <stdio.h>
Fig. 1.7.2
void main()
l.8 Complexity in Terms of Time and
int i, n, sum, x;
Space
sum =0;
L8.1 Algorithm Analysis printf("\n enter no of data to be added");
Q Explain time and space complexity with example. scanf("%d", &n);
S-15, W-15, W-16, S-18, W-19, S-22 for (i =1;i<=n;it+)
S-16
0. How an algorithm ís analysed ?
a. Define complexity and classify it. S-17, W-22 scanf("%d", &x);
Q. Describe time and space trade off and time and space Sum = Sum + X;

complexíty with exarnple of each. S-17, W-17


printf("n sum =%d", sum):
Most often there are many algorithms for solving a
problem. On what basis should we choose an
algorithm? There are often two contradictory goals. Space requirement =Space required to store the
variables i, n, sum and x =2 +2+2 + 2 =8
() Algorithm should be easy to understand, write
and debug (an integer requires 2 bytes of memory space.]
(i) Algoríthm should make efficient use of Calculation of computation time
computer resources like CPU, memory etc.
Computation
When we write a program to be used a few times, Statement Frequency time
goal (i) is most important. Cost of writing the
Sum ) 1 t
program will have an upper hand over the cost of
running the program, when the program is to be printf ("\n Enter no of data 1 t
used many times, the cost of running the program
TechKaowtedge
Introduction to Data Structta
Data Structure Using C 1-12

Soln. :
Statement Frequency Computation
tlme Statement No. Frequency
1
to be added"):
2 n+1
scanf("%d", &n) 1
3
for (i =1 ;i<=n;it+) n+1 (n+1) t, n
4
scanf ("%d", &x) n nt,
1,8.2 Measuring the Running Time of a
Sum sum +X n nt, Program (Time Complexity)
|printf("\n sum =%d", sum) t; Running time of a program can be judged on the
basis of factors such as:
Total computation time
1. Input to the program.
: t;+ty+t, +n(t+ ts tte) +t,tt,
2 Size of the program.
T= n(t+ t;+ te) +(t; +t;+tgt t4tt) 3 Machine language instructionset.
For large n, Tcan be approximated to 4 The machine we are executing on.
T n (t,+ t;+ t) =kn 5 Time required to execute each machine instruction.
where 6. The time complexity of the algorithm of the
k = tt ts + 7 . . aconstant value. program.

Thus, T = kn 1.8.3 Measurement of Growth Rate


(Asymptotic Growth Rate)
T« n
1.8.3(A) Asymptotic Consideration
() t ,tz ..t, are computer dependent, on a faster
computer, the execution time of an instruction will When considering timecomplexities f,(n) andf,(n)
be less. of two different algorithms fora given problem of size n,
(ii) for (i= 1; i<=n; i++), will be executed n+1times we need to consider and compare the behaviour of the
and notntimes. For allvalues of ibetween 1and n, two functions only for large n. If the relative behaviour of
the condition i< =nwill evaluate to true and when i twofunctions for smaller values conflict with the relative
becomes n+1, the condition i< = n will evaluate to behaviour for larger values, then we ignore the
false. Thus the above instruction will be executed conflicting behaviour for smaller values. For example,
n+1times. consi.der the following functions.

Ex, 1.8.1: Determine the frequency count for all statements ,{(n) =100 n', f2 (n) =5 n'
in the foliowing program segment Representing time complexities of two solutions of
i= 1; a problem.
2. whise (i <e n) f,(n) ,(n)
100
5 2500 625
4 10 10000 5000

20 40000 40000

Tech Knouledge
Using C 1-13 introduction to DataStructures
Data Structure
s 20 1.9 The Notation O: (Pronounced as
f, (n) 2f, (n) for n
We would still prefer the solution having f,(n) as
big-oh), (O(n) is Pronounced as big
time complexity because, fi(n)sfh(n) for all
n> 20. oh of n')]
1.8.3(B) Constant Factor in Complexity Q Define Big 'O Notation. W-16

Measure
Provides asymptotic upper bound for a given
Let us consider an algorithm having a timing functions. Let f(x) and g(x) be two functions then f(x) is
complexity given by the function f(n)=100n' said to be O(g(x)) if there exist two positive integer/real
number constants c andk such that
where [100- a constant, n - size of the problem].
The time required for solving a problem, depends f(x) < cg(x) for all x 2k
not only on the size of the problem but also, on the The constant k is due to asymptotic consideration
hardware and software used to execute the and the constant c for hardware/software environment.
solution. The effect of hardware and software on
Ex. 1.9.1:f(x) =x +5x
the time required may closely be approximated by a
constant.
g(x) =x let us takec=2
Soln. :
Suppose, a new Computer executes aprogram tWo
X x²+ 5x 2x?
times aster than another computer. Then
irrespective of the size of the problem, the new 1 5 2

computer solves the problem roughly two times 2 14 f(x) s cx?


faster than the computer. Thus we conclude that the 5 50 50 For x 2 5
time requirement for execution of a solution,
(asymptotic behavior)
changes by aconstant factor on change in hardware
or software. f(x) s cg (x) for allx2kwhere c= 2 and k =5
discussion
An important consequence of the above
is that if the time taken by one machine in executing Ex. 1.9.2 : For the function defined by
f(x) =5x°+ 6x´+1 show that f(x) =O(x)
a solution is of the order of n (say), then time take
by every machine is of the order of n'. Thus, Soln. :
function different from each other by constant f(x) = 5x +6x' +1 s5x' + 6x³+ 1x° for all x>1
factor, when treated as time complexities, should or, f(x)< 12x² forx1
not be treated as different. i.e. should be treated as

complexíty wise same.


(by replacing each term of x by the highest degree
term x)
Following functions have the same time
there exist c =12 and k= 1 such that
complexities :
f, (n) =5 n', f, (n) =100 n f(x) s cx* for allx k

t,(n) =1000 n', f, (n) = n Hence f(x) is O(x)


Time complexity of f, (n) = Time complexity of f; (n) Note: Time complexity of a polynomial s same as
= Time complexity off,(n) the time complexity of the highest degree
term.
= Timecomplexity of f,(n)

TechKaowledge
Data Structure UsingC 1-14 Introduction to Data Structurec

Caiculating the running time of a program statement will be executed is called its frequencu
count. Frequency count may vary from data set to
Ex. 1.9.3: Arrange the folowing computing tunctions as per
data set.
their growth rate. log, n, n, nlog, n, n,n',2".
Soln.: The constant factor incomplexity measure
Common computing functions and their growth Let us consider an algorithm having a timing
rates
complexity given by the function f (n) =100 n?
log, n n nlog,n n 2 where, [100- a constant, n - size of the problem].

1 1 1
The time requíred for solving a problem, depends
2
not only on the size of the problem but also on the
1 2 2 4 8 4 hardware and software used to execute the
solution. The effect of hardware and software on
4 16 64 16 the time required may closely be approximated by a
constant.
8 24 64 512 256
Suppose, a new computer executes a program two
4 16 64 256 4096 65536 times faster than another computer. Then

32 160 1024 32768|2, 147, 483, 648 irrespective of the size of the problem, the new
computer solves the problem roughly two times
Thus, 0(2n) >0(n°) >0(n) >Ofn log, n) > 0(n) > faster than thecomputer. Thus we conclude that the
O(log, n) time requirement for execution of a solution,
Ex. 1.9.4 : Give time complexity of any four sorting
changes by a constant factor on change in hardware
or software.
aigorithms.
Soln. : An important consequence of the above discussion
is that if the time taken by one machine in executing
1 Bubble sort - 0(n) asolution is of the order of n (say), then time take
2 Selection sort -0(n) by every machine is of the order of n', Thus,
function different from each other by constant
3 insertion sort- 0(n)
factor, when treated as time complexities, should
4 Merge sort - 0(n log n) not be treated as different. i.e. should be treated as

Ex. 1.9.5 : What do you mean by frequency count ? Why complexity wise same.
only frequency count is important in deciding the time Following functions have the same time
complexity of an algorithm ? complexities :
Soin.:
, (n) = Sn?
Total time taken by a statement in execution
depends on : f,(n) = 100n?
(i) The amount of time a single execution will take. f, (n) = 1000n²
(i) Number of times the given statement will be f, (n) = n?
executed. Time complexity of f,(n)= Time complexity of f, (n)
The product of these numbers will be the total time = Time complexity of f; (n)
taken by the statement. Number of times a
=Time conmplexity of f, (n)

You might also like