Data Structure
Data Structure
Data Structure
In data structure, we study that how many ways are there to organize data. It means the
different possible ways of representing the data items in Computer memory.
Logical or mathematical model of a particular organization of data is called a data
structure .The choice of a particular data model depends on two considerations.
o it must be rich enough in structure to represent the actual relationships of the
data in the real world.
o the structure should be simple enough that one can effectively process the data
when necessary
Data structure Is a particular way of storing and organizing data in a computer so that it
can be used efficiently
Different kinds of data structures are suited to different kinds of applications and some
are highly specialized to specific tasks
used.
Algorithm
An algorithm is a finite set of instructions, which accomplishes a particular task.
OR
Finiteness: It means that algorithm must terminate in the finite number of steps.
Effectiveness: Every algorithm must be effective which performs some specific Action on
ALGORITHM NOTATION
A complete algorithmic notation is given below.
Name of algorithm: Every algorithm is given an identifying name, written in capital
letters.
Introductory Comments: The algorithm name is followed by a brief description of the
tasks the Algorithms perform.
Steps: The algorithm is made of a sequence of numbered steps.
Comments: An algorithm step may terminate with a comment enclosed in bracket,
which is used to help the reader better understand that step.
Algorithm – SUM
This algorithm get two numbers and to calculate their sum.
1. INPUT first number in N
2. INPUT second number in M
3. Add N to M and store result in s, i.e. s = N + M
4. Print s
5. End
Selection Statements
Selection statements are used for making decisions. The decision is made by testing a
given condition. After testing a condition, a statement or a set of statements are executed or
ignored. The structure that implements this logic in a programming language is called
conditional structure. A conditional statement is represented by the IF structure. It has one of
the following two forms:
1– IF condition THEN
Statement (s)
End IF
In the first “IF structure”, the statements following the “IF structure” are executed when
the given condition is true. Otherwise, these statement(s) are ignored.
In the second “IF structure”, one of the two blocks of statements are executed. If the
given condition is true, then the block of statements under “IF statement” is executed
otherwise the block following the “ELSE statement” will be executed.
1. Start
2. Input Three Numbers A, B & C.
3. IF A > B THEN
IF A > C THEN [Nested If Structure]
PRINT “A is greater”
ELSE
PRINT “C is greater”
END IF
ELSE
IF B > CTHEN
Looping Statements
The looping statements are used to execute certain statement (s) repeatedly.
The statements that are executed repeatedly are called body of loop. In algorithm notation,
“Repeat” statement is used to execute the statements repeatedly. The “Repeat” statement has
two different forms:
The REPEAT FOR loop structure uses an index variable to control the number of
iterations of the loop. In the above syntax ‘Index’ is the control variable.
1. Start
2. REPEAT Step – 3 FOR C = 1 To 10 BY 1
3. PRINT C
[End of step – 2 Loop]
4. Exit
Repeat WHILE Structure
This loop structure is used to execute a statement or a set of statements repeatedly
until the given condition remains true. It is also referred to as conditional loop. Its general
syntax is:
The condition is tested at the beginning of the loop. There must be a statement in the body of
the loop that will change the condition during the execution of the program to bring it near the
specified condition.
1. C = 1
2. Repeat Steps 3 To 4 WHILE (C <=10)
3. PRINT C
4. C = C + 1
[End of Step – 2 Loop]
5. Exit
The RETURN statement is used as the last statement of the sub-algorithm to return the
control back to the calling program.
Type of Sub-Algorithm
The sub-algorithm is divided into two categories:
1- Function sub-algorithm
2- Procedure sub-algorithm
Both sub-algorithms are independent modules and are written to perform specific tasks.
The difference between the two that:
The function sub-algorithm returns a single value to the calling algorithm through
RERUN statement.
Procedure sub-algorithm may return more than one values. It returns values through
parameters.
The function sub-algorithm is called as an expression or as a variable. The returned
value is used in an expression.
The procedure sub-algorithm is called by the CALL statement in algorithms.
Function: Mean (A, B, C)
Write a function sub-algorithm to find the average of three numbers.
MEAN (A, B, C)
1 AVG = (A+B+C)/3
2 Return (AVG)
Exchange (A, B)
1 TEMP = A
2 A = B
3 B = TEMP
4 RETURN
EXAMPLE
(a) Let DATA be a 6-element linear array of integers such that
DATA [1] = 247 DATA [2] = 56 DATA [3] = 429 DATA [4] = 135 DATA
[5] = 87 DATA [6] = 156
Sometimes we will denote such an array by simply writing
DATA: 247, 56, 429, 135, 87, 156
The array DATA is frequently pictured as in Fig. (a) or Fig. (b).
DATA
1 247
2 56 DATA
3 429
247 56 429 135 87 156
4 135
5 87 1 2 3 4 5 6
6 156
(a) (b)
(b) An automobile company uses an array AUTO to record the number of automobiles sold
each year from 1932 through 1984. Rather than beginning the index set with 1. If is
more useful to begin the index set with 1932 so that
The total number of elements of a two-dimensional array having m rows and n columns is m x
n. For example, an array having 2 rows and 4 columns has 2 x 4 = 8 elements.
Each programming language has different rules to declare multi-dimensional arrays. In
C++, a two-dimensional array “temp” of integer data type having 6 rows and 4 columns is
declared as:
Int temp [6] [4] ;
Representation of Two-Dimensional Arrays In Memory
Two-dimensional arrays are represented in memory in two ways. These are Row-major
order and Column-major order.
In row-major order, a two-dimensional array is represented in memory by row order.
For example, a two-dimensional array having 2 rows and 3 columns is stored in row-major
order as:
{X[1, 1], X[1, 2], X[1, 3]}, {X[2, 1], X[2, 2], X[2, 3]}
In column-major order, a two-dimensional array is represented in memory by column
order. For example, a two-dimensional array having 2 rows and 3 columns is stored in
column-major order as:
{X[1, 1], X[2, 1]}, {X[1, 2], X[2, 2]}, {X[1, 3], X[2, 3]}
Bibliography
1. Data Structures by SEYMOUR LIPSCHUTZ ( SCHAUM `S Outlines)
2. Data Structures in C++ By Muhammad Tauqeer ( AIKMAN SERIES)
3. Data Structures and Algorithms in C++ by Michael T. Goodrich, Roberto Tamassia and
David Mount (WILEY)
Or:
A stack is a list of elements in which an element may be inserted or deleted only at one
end, called the top of the stack. This means, in particular, that elements are removed from a
stack in the reverse order of that in which they were inserted into the stack.
(a) “Push” is the term used to insert an element into a stack.
(b) “Pop” is the term used to delete an element from a stack.
These terms are used only with stacks, not with other data structures.
EXAMPLE
Suppose the following 6 elements are pushed, in order, onto an empty stack:
(a) (b)
AAA BBB CCC DDD EEE FFF …
1 2 3 4 5 6 7 8 9 … N–1 N
TOP
Fig. Diagrams of stacks.
STACK
XXX YYY ZZZ
1 2 3 4 5 6 7 8
TOP 3 MAXSTK 8
Fig
Frequently, TOP and MAXSTK are global variables; hence the procedures may be called
using only
PUSH(STACK, ITEM) and POP(STACK, ITEM)
Respectively. We note that the value of TOP is changed before the insertion in PUSH but the
value of TOP is changed after the deletion in POP.
EXAMPLE
(a) Consider the stack in Fig. we simulate the operation PUSH(STACK, WWW):
Evaluation of Expressions
An arithmetic expression is made up of operands, arithmetic operators and parentheses.
The operands may be numeric variables or numeric constants. Following are some examples of
arithmetic expressions:
A+B, X*Y, A*(B-C)/2, (A+B)^2
The arithmetic operators +, -, * and / are the same that are used in ordinary algebra. The
operator ^ is used as to compute the exponential. This operator is not available in C++. Instead
‘pow’ function is used to calculate the exponential. The expression is always evaluated from left
to right. The order in which the expression is evaluated is:
Step-1: The expression is evaluated from left to right. Exponential is evaluated first. After
evaluating the exponential, the expression becomes:
= 8 + 6*2 - 9/3
Step-2: Multiplication and division are performed nest and the expression becomes:
= 8 + 12 - 3
Step-3: Addition and subtraction are performed last, from left to right, and the final
result is;
= 17
Since the operators are used before the operands in polish notation, it is also called
prefix notation. The polish notation is named in honour of polish mathematics Jan Lukasiewiez.
Parenthesis are not used in polish notation.
Prefix Postfix
Infix
(Polish notation) (Reverse Polish notation)
A+B +AB AB*
A*B *AB AB*
A/B /AB AB/
A-B -AB AB-
The computer evaluate an expression given in infix notation by converting it into postfix
notation. The stack is used to perform this operation.
The following steps are taken to evaluate a postfix expression:
Example:
Consider the following arithmetic expression P written in postfix notation:
P: 5, 6, 2, +, *, 12, 4, /, ₋
Symbol Scanned STACK
(1) 5 5
(2) 6 5, 6
(3) 2 5, 6, 2
(4) + 5, 8
(5) * 40
(6) 12 40, 12
(7) 4 40, 12, 4
(8) / 40, 3
(9) – 37
1. (A+B) *C
2. A+ (B*C)
3. A+B*C+ (D*E+F) *G
(ii) A+ (B*C)
Steps Symbol Scanned Stack Output
1 A ( A
2 + (+ A
3 ( (+ ( A
4 B (+ ( AB
5 * (+ ( * AB
6 C (+ ( * ABC
7 ) (+ ABC*
8 ) Empty ABC* +
Representation of Queues
Queues may be represented in the computer is usually be means of one-way lists or
linear arrays. Each of our queues will be maintained by a linear array QUEUE and two
pointer variables: FRONT, containing the location of the front element of the queue; and
REAR, containing the location of the rear element of the queue. The condition FRONT =
NULL will indicate that the queue is empty
Observe that whenever an element is deleted from the queue, the value of FRONT is
increased by 1; this can be implemented by the assignment
FRONT = FRONT + 1
Similarly, whenever an element is added to the queue, the value of REAR is
increased by 1; this can be implemented by the assignment
REAR = REAR + 1
QUEUE
1 2 3 4 5 6 7 ... N
(a)
QUEUE
FRONT: 2
REAR: 4 BBB CCC DDD ...
1 2 3 4 5 6 7 ... N
(b)
QUEUE
FRONT: 2
REAR: 6 BBB CCC DDD EEE FFF ...
1 2 3 4 5 6 7 ... N
(c)
QUEUE
FRONT: 3
REAR:(d) 6 CCC DDD EEE FFF ...
1 2 3 4 5 6 7 ... N
(d)
QUEUE is circular, that is, that QUEUE[1] comes after QUEUE[N]. in the array.
With this assumption, we insert ITEM into the queue by assigning ITEM to QUEUE[1].
Specifically, instead of increasing REAR to N + 1, we reset REAR = 1 and then assign
QUEUE[REAR] = ITEM
Similarly, if FRONT = N and an element of QUEUE is deleted, we reset FRONT = 1
instead of increasing FRONT to N + 1.
Suppose that our queue contains only one element, i.e., suppose that
FRONT = REAR ≠ NULL
And suppose that the element is deleted. Then we assign
FRONT = NULL and REAR = NULL
To indicate that the queue is empty
DEQUE
LEFT: 4
RIGHT: 7 AAA BBB CCC DDD
1 2 3 4 5 6 7 8
(a)
DEQUE
LEFT: 7
RIGHT:(b) 2 YYY ZZZ WWW XXX
1 2 3 4 5 6 7 8
(d)
There are two variations of a deque-namely, an input-restricted deque and an output-restricted deque.
Specifically, an input-restricted deque is a deque which allows insertions at only one end of the list but
allows deletions at both ends of the list; and an output-restricted deque is a deque which allows
deletions at only one end of the list but allows insertion at both ends of the list.
PRIORITY QUEUES
A priority queue is a collection of elements such that each element has been assigned a priority and such
that the order in which elements are deleted and processed comes from the following rules:
(1) An element of higher priority is processed before any element of lower priority.
(2) Two elements with the same priority are processed according to the order in which they
were added to the queue.
A prototype of a priority queue is a timesharing system: programs of high priority are processed first,
and programs with the same priority from a standard queue.
(a) Each node in the list will contain three items of information: an information field INFO, a priority
number PRN and a link number LINK.
(b) A node X precedes a node Y in the list (1) when X has higher priority than Y or (2) when both
have the same priority but X was added to the list before Y. this means that the order in the
one-way list corresponds to the order of the priority queue.
Priority numbers will operate in the usual way: the lower the priority number, the higher the priority.
Searching & sorting are two most important operations that are frequently performed on data
structures. These are fundamental operations in computer science. These are mostly performed on data
structures like arrays, linked lists.
SEARCHING
Computer systems are often used to store large amounts of data from which individual records
are retrieved according to some search criterion. The process of finding a specific data item or record
from a list is called searching.
The efficient storage of data to facilitate fast searching is an important task. All other operations like
inserting, deletion, etc. are dependent on this operation. For example, to delete a data item from a list,
its position is first located in the list and then the deletion operation is performed.
The search is successful if the specified data item or record is found during searching process.
Search operation terminates when it is successful. If the specified data is not found then the search is
unsuccessful. Different techniques are used to carry out search operations. The commonly used
searching methods are:
Sequential Search
Binary Search
Sequential Search
The sequential search is a simple and straightforward technique to search a specified item in an
unordered list. The specified value is searched in the list sequentially, i.e. starting from the first element
to the last element in the list in a sequence. When the required value is found, search operation stops.
The sequential search is a slow process. It is used for small amounts of data. This method is not
recommended for large amount of data.
BINARY SEARCH
LINEAR SEARCHING
In linear search, we access each element of an array one by one sequentially and see whether it is
desired element or not. A search will be unsuccessful if all the elements are accessed and the desired
element is not found.
Therefore linear search can be defined as the technique which traverses the array sequentially to locate
the given item.
Algorithm
Here a is a linear array with n elements, and item is a given item of information. This algorithm finds the
location loc of item in a, or set 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 = 1.
3. [Search for item ]
Repeat while data [loc] =! item:
Set loc = loc + 1.
4. Successful] if loc = n + 1, then set loc = 0.
5. Exit.
BINARY SEARCHING
Binary search is an extremely efficient algorithm. This search technique searches the given item in
minimum possible comparisons. To do the binary search, first we had to sort the array elements. The
logic behind this technique is given below :
First find the middle element of the array.
Compare the mid element with an item
There are three cases :
(a) If it is a desired element then search is successful.
(b) If it is less than desired item then search only the first half of the array.
(c) If it is greater than the desired element search in the second half of the array
Searched in 1st half of array Mid value Searched in 2nd half of array
First value Mid = (First + last)/2 Last value
9 12 24 30 36 45 70
0 1 2 3 4 5 6
Beg Last
0 1 2 3 4 5 6
9 12 24 30 36 45 70
beg Last
4 5 6
36 45 70
a[mid] i.e. a[5] is 45.
45 = 45
Search successful ! ! At location number 5 (element number 6).
SORTING
Let p be a list of m elements p1, p2, p3 , . . ., pn in memory. Sorting p means arranging the contents of p
in either increasing or decreasing order i.e.,
p1≤ p2 ≤ p3 ≤ p4 ≤ p5 . . . ≤pn
There are m elements in the list, therefore there are m! ways to arrange them.
Example
Suppose an array value contain 10 elements as follows:
VALUE : 7, 9, 3, 6, 8, 2, 1, 4, 18, 5
After Sorting, VALUE must appear as
VALUE : 1, 2, 3 4, 5, 6, 7, 8, 9, 18
BUBBLE SORT
In bubble sort, each element is compared with its adjacent element. If the first element is larger than
the second one then the position of the elements are interchanged, otherwise it is not changed. Then
next element is compared with its adjacent element and the same process is repeated for all the
elements in the array. During the pass, the second largest element occupies the second last position.
During the next pass, the same process is repeated leaving the largest element. During this pass, the
largest element occupies the n-1 position. The same process is repeated until no more elements are left
for comparison.
Finally the array is sorted one.
The various steps involved in sorting of an array of 5 elements are given as under :
INITIAL ELEMENTS (without sorting)
11
15
2
13
6
Pass 2. Find the location loc of the smallest in the sub list of n – 1 elements
a[2], a[3], . . , a[n], and then interchange a[loc] and a[2]. Then :
a[1], a[2] is stored, since a [1] ≤ a[2].
Pass 3. Find the location loc of the smallest in the sub list of n-2 elements
a[3], a[4], . . , a[n], and then interchange a[loc] and a[3]. Then :
a[1], a[2], . . , a[3] is stored, since a[2] ≤ a[3].
... .......................................................................
... .......................................................................
Pass n – 1. Find the location loc of the smaller of the elements a[n – 1], a[n], and then interchange
a[loc] and a[n – 1]. Then :
a[1], a[2], . . , a[n] is stored, since a[n – 1] <<=a[n].
Thus a is sorted after n – 1 passes.
For example, suppose we have a list, which contains the elements: 40, 30, 50, 20 and 10. If we want to
sort this list of elements using the selection sort technique.
Therefore, interchange a[0] & a[4] i.e., 11 & 2 to obtain following array
Therefore, interchange a[0] & a[2] i.e., 11 & 2 to obtain following array
Algorithm
Procedure min (a, k, n, loc)
An array a is in memory. This procedure finds the location loc of the smallest element among
a[k], a[k + 1], . . , a[n] during k pass. min (a, k, n, loc)
Algorithm
Selection sort A[MAXSIZE], N)
This algorithm can now be easily started
1. Repeat steps 2 and 3 for k = 1, 2, . . , n – 1:
2. Call min(a, k, n, loc).
3. [Interchange a[ k ] and a[loc].]
Set temp : = a[ k ], a[ k ] : = a[loc] and a[loc] : = temp.
[End of step 1 loop.]
4. Exit.
The selection sort makes first pass in n – 1 comparisons, the second pass in n – 2 comparisons and so on.
The total number of comparisons are ((n – 1) + (n + 2)) + . . . . + 1 = n(n – 1) /2 which is O(n2). Selection
INSERTION SORT
An insert5ion sort is one that sorts a set of values by inserting values into an existing sorted file.
Suppose an array a with n elements a[1], a[2], . . , a[n] is in memory. The insertion sort algorithm scans a
from a[1] to a[n], inserting each element a[k] into its proper position in the previously sorted subarray
a[1], a[2], . . , a[k – 1]. That is :
Pass N. a[n] is inserted into its proper place in a[1], a[3], . . , a[n – 1] so that :
a[1], a[2], . . , a[n] is sorted.
To illustrate the insertion sort method, consider the following array a with 7 elements :
25, 15, 30, 9, 99, 20, 26
Array a of 7 elements
25 15 30 9 99 20 26
0 1 2 3 4 5 6
15 25 30 9 99 20 26
0 1 2 3 4 5 6
Pass II: a[2] > a[1], position of elements remains same.
15 25 30 9 99 20 26
0 1 2 3 4 5 6
Pass III: a[3] is less than a[0], a[1] and a[2], so insert a[3] before a[0], we get.
a[5] before a[2], we get
9 15 25 30 99 20 26
0 1 2 3 4 5 6
Pass IV: a[4] > a[3], no change is performed.
9 15 25 30 99 20 26
Pass V: a[5] is less than a[2], a[3] and a[4], therefore insert a[5] before a[2], we get
9 15 20 25 30 99 26
0 1 2 3 4 5 6
Pass VI: Now a[6] is less than a[4], a[5] therefore insert a[6] before a[4], giving the following
array :
9 15 20 25 26 30 99
0 1 2 3 4 5 6
Step 1 : [Initially]
low = l
high = h
key = a [(l + h)/2] [Middle element of the element of the list]
Step 2 : Repeat through step 7 while (low <= high)
Step 3 : Repeat step 4 while (a([low] < key))
Step 4 : low = low + 1
Step 5 : Repeat step 6 while (a([high] < key))
Step 6 : high = high – 1
Step 7 : if(low <= high)
(a) temp = a[low]
(b) a[low] = a[high]
(c) a[high] = temp
(d) low = low + 1
(e) high = high – 1
Step 8 : if(l<high)) Quick_sort (a, l, high)
Step 9 : if (low<h) Quick_sort (a, low, h)
Step 10 : Exit