1. Data Structure and Algorithm
Prepared by Basharat Jehan
Email: Basharat_jehan@yahoo.com
2. Data
• Facts or information used usually to calculate,
analyze, or plan something.
OR
• Data are simply collection of facts and figures.
Data are values or set of values.
OR
The quantities, characters, or symbols on which
operations are performed by a computer, being
stored and transmitted in the form of electrical
signals and recorded on magnetic, optical, or
mechanical recording media.
3. • In computing, data is information that has
been translated into a form that is more
convenient to move or process.
• Data is collected and analyzed to create
information suitable for making decisions
4. • Data items that are divided into sub items are
group items;
• those that are not are called elementary
items. For example, a student’s name may be
divided into three sub items – [first name,
middle name and last name]
• but the ID of a student would normally be
treated as a single item.
5.
6. Information
• Knowledge that you get about someone or
something.
• knowledge obtained from investigation, study, or
instruction (2) : intelligence, news (3) : facts,
data .
• Data are converted to information after
Processing.
• knowledge gained through study,
communication, research, instruction, etc.;
factual data:
7. • Data that is (1) accurate and timely, (2)
specific and organized for a purpose, (3)
presented within a context that gives it
meaning and relevance, and (4) can lead to an
increase in understanding and decrease in
uncertainty.
15. Physical and Logical Data Structures
• A physical data structure refers to the actual
organization of data on a storage device. The
logical data structure refers to how the
information appears to a program or user. For
example, a data file is a collection of
information stored together. This is its logical
structure. Physically, however, a file could be
stored on a disk in several scattered pieces.
17. INTRODUCTION
• An algorithm is an effective method expressed
as a finite list of well-defined instructions for
calculating a function
18. COMPUTER ALGORITHMS
• In computer systems, an algorithm is basically
an instance of logic written in software by
software developers to be effective for the
intended "target" computer(s) for the target
machines to produce output from
given input (perhaps null)
19. DEFINITION
• An algorithm is a finite sequence of step by
step, discrete, unambiguous instructions for
solving a particular problem
– has input data, and is expected to produce output
data
– each instruction can be carried out in a finite
amount of time in a deterministic way
20. Control structures
• Programs written in procedural languages, the
most common kind, are like recipes, having lists
of ingredients and step-by-step instructions for
using them. The three basic control structures in
virtually every procedural language are:
1. Sequence—combine the liquid ingredients, and
next add the dry ones.
2. Conditional—if the tomatoes are fresh then
simmer them, but if canned, skip this step.
3. Iterative—beat the egg whites until they form
soft peaks.
21. SEQUENCE
• it is the default control structure; instructions
are executed one after another. They might,
for example, carry out a series of arithmetic
operations, assigning results to variables, to
find the roots of a quadratic
equationax2 + bx + c = 0. The conditional IF-
THEN or IF-THEN-ELSE control structure allows
a program to follow alternative paths of
execution.
22. ITERATIVE/REPETITIVE FLOW
• Iteration (also called repetition) means a frame
that regulates the repeat of an action depending
on a condition. The action is called the body of
the iteration loop.
• This means that all low or high level algorithms
can be formulated as a series of structural
elements consisting only of the three types
above.
• Hence, for any algorithm description method it is
enough to be able to interpret the three types
above.
24. ITERATION, OR LOOPING AND
CONDITIONAL FLOW
• It gives computers much of their power. They can
repeat a sequence of steps as often as necessary, and
appropriate repetitions of quite simple steps can solve
complex problems.
• These control structures can be combined. A sequence
may contain several loops; a loop may contain a loop
nested within it, or the two branches of a conditional
may each contain sequences with loops
and more conditionals. The following programming
fragment employs the IF-THEN structure for finding
one root of the quadratic equation, using the quadratic
formula:
25. Array data structure
• In computer science, an array data structure
or simply an array is a data structure
consisting of a collection of elements (values
or variables), each identified by at least one
array index or key.
26. FINDING LENGTH OF ARRY
• MAXIMUM LENGTH=
UPPER BOUND(UB)-LOWER BOUND(LB)+1
27. One dimensional (1-D) arrays or
Linear arrays:
• In it each element is represented by a single
subscript. The elements are stored in
consecutive memory locations. E.g. A [1], A
[2], ….., A [N].
• Or
• A(1), A(2)…
• A1,A2,…………
28. Multi dimensional arrays: Two
dimensional (2-D) arrays or Matrix
arrays
• In it each element is represented by two
subscripts. Thus a two dimensional m x n array
A has m rows and n columns and contains
m*n elements. It is also called matrix array
because in it the elements form a matrix. E.g.
A [2] [3] has 2 rows and 3 columns and 2*3 = 6
elements.
29. Traversing
• Traversing basically means the accessing the
each and every element of the array at least
once. Traversing is usually done to be aware of
the data elements which are present in the
array.
30. ALGORITHM FOR TRAVERSING
• SET K=LB
• REPEAT STEP 3 AND 4 WHILE K<=UB
• INPUT ARRAY[K]
• SET K=K+1
• END LOOP
• OUTPUT ARRAY[K]
• EXIT
31. A program to traverse or read a linear
or 1-D array
• #include<stdio.h>
#include<conio.h>
void main()
{
int a[7], i=0;
clrscr();
printf("Enter the elements of the array :");
for (i=0;i<=6 ;i++ )
{
scanf("%dn", &a[i]); /* taking input array from the user */
}
printf("nThe elements of the array you have enetered are as follows :")
for(i=0; i<=6; i++)
{
printf("%d", a[i]); /* printing the array elements or traversing the array */
}
getch();
}
32. Algorithm to find the sum of elements
of array
• Step#1 SUM=0
• Step#2 repeat for i=0 to UB
• [print the calculated sum]
• SUM=SUM+A[i]
• End of Loop
• Step#3 PRINT SUM
• Step#4 EXIT
34. Accessing One Dimensional array by
Dope Vector method
• L(X[k])=Lo+C*(k-1)
• Where Lo is base address, C is the length of
each memory location, and k is index number.
• L(X[3]) = 200+2*(3-1)=204
Data address
45 200
45 202
56 204
67 206
88 208
38. Inserting
• Inserting: Adding a new record to the end of
array.
• Insertion may be at end of array or at specific
location.
39. • Adding a new record to the end of array.
• Algorithm
• REPEAT step 2 to 3 FOR I=4 to 9
• INPUT value in N
• Temp[I]= N
[End of step- 2 Loop]
Exit
41. Element insertion at specific location
• Algorithm to insert element in array requires
the specific location at which the element is
to be added.
42.
43. • This algorithm performs Insert Operation on
Array; it adds an ELEMENT at the given
location LOC in the array – DATA. In the first
step we initialized variable I with the
maximum number of element present in the
array (I:=N). After that with loop we shift the
element forward till we reach the location
LOC. In the next step, we insert the ELEMENT
at its location.
49. Delete Operation on Array
• To delete element from array we should know the
location from where we want to delete.
Algorithm to Delete Element from Array can be
executed at any location ie. at it beginning, in
middle or at the end of the array.
• Apply a loop from the location of item till the end
of the array. Shift the element forward. In this
algorithm, DATA is an array. ELEMENT is the value
which we want to delete from the location LOC. N
is the maximum number of element present in
the array DATA.
53. INTRODUCTION TO THE BASIC
OPERATIONS OF DATA STRUCTURE
• The data appearing in data structures are
processed by means of operations. The
following are operations are major operations
54. • Traversing: Accessing each record exactly once
so that certain items in the record may be
processed.
• Searching: Finding the location of the record
with a given key value, or finding the locations
of all records which satisfy one or more
conditions.
• Inserting: Adding a new record to the
structure.
• Deleting: Removing a record from the
structure. It is used to delete an existing data
item from the given collection of data items
•
55. Following two are special operations:
Following two are special operations:
• Sorting: Arranging the records in some logical
order. It is used to arrange the data items in
some order i.e. in ascending
or descending order in case of numerical
data and in dictionary order in case of
alphanumeric data
• Merging: Combining the records in two
different sorted files into a single sorted file.
56. Recursion Concept :
• Recursion is basic concept in Programming.
• When Function is defined in terms of itself
then it is called as “Recursion Function“.
• Recursive function is a function which
contains a call to itself.
60. Fibonacci Sequence
• The Fibonacci Sequence is the series of
numbers: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ... The
next number is found by adding up the two
numbers before it. Similarly, the 3 is found by
adding the two numbers before it (1+2),
61. Fibonacci series program in c using
recursion
• #include<stdio.h>
•
• int Fibonacci(int);
•
• main()
• {
• int n, i = 0, c;
•
• cin>>n;
•
• cout<<"Fibonacci series;
•
• for ( c = 1 ; c <= n ; c++ )
• {
• cout<<Fibonacci(i);
• i++;
• }
•
• return 0;
• }
•
62. • int Fibonacci(int n)
• {
• if ( n == 0 )
• return 0;
• else if ( n == 1 )
• return 1;
• else
• return ( Fibonacci(n-1) + Fibonacci(n-2) );
• }
63. Searching Algorithms
• Necessary components to search a list of fdata
– Array containing the list
– Length of the list
– Item for which you are searching
• After search completed
– If item found, report “success,” return location in array
– If item not found, report “not found” or “failure”
64. Sequential Search
• In computer science, linear search or
sequential search is a method for finding a
particular value in a list that checks each
element in sequence until the desired element
is found or the list is exhausted. The list need
not be ordered.
65. • Suppose that you want to determine whether 27 is in the list
• First compare 27 with list[0]; that is, compare 27 with
35
• Because list[0] ≠ 27, you then compare 27 with
list[1]
• Because list[1] ≠ 27, you compare 27 with the next
element in the list
• Because list[2] = 27, the search stops
• This search is successful!
Searching Algorithms (Cont’d)
Figure 1: Array list with seven (07) elements
66. • Let’s now search for 10
• The search starts at the first element in the list; that
is, at list[0]
• Proceeding as before, we see that this time the
search item, which is 10, is compared with every
item in the list
• Eventually, no more data is left in the list to compare
with the search item; this is an unsuccessful search
Searching Algorithms (Cont’d)
67. Algorithm of Sequential Searching
• The complete algorithm for sequential search is
//list the elements to be searched
//target the value being searched for
//N the number of elements in the list
SequentialSearch( LIST, ITEM, N, LOC)
Set LOC=1
• for i = 1 to N do
• INPUT LIST[i]
• Repeat While(LOC<=N)
• if (ITEM = LIST[LOC])
• return LOC [Successful Search]
• LOC=LOC+1
• end if
• end While
• return 0 [Unsuccessful Search]
68. C++ Code for Sequential Search
• #include<iostream>
• #include<conio.h>
• using namespace std;
• main()
• {
• int A[10],i, LOC, ITEM,n;
• LOC=-1;
• cout<<"Enter size of array but less than 10";
• cin>>n;
69. • for (i=1; i<=n; i++)
• {
• cin>>A[i];
• }
• cout<<"item to be searched";
• cin>>ITEM;
72. • Can only be performed on a sorted list !!!
• Uses divide and conquer technique to search list
Binary Search Algorithm
73. • Search item is compared with middle element of
list
• If search item < middle element of list, search is
restricted to first half of the list
• If search item > middle element of list, search
second half of the list
• If search item = middle element, search is
complete
Binary Search Algorithm (Cont’d)
74. • Determine whether 75 is in the list
Binary Search Algorithm (Cont’d)
Figure 2: Array list with twelve (12) elements
Figure 3: Search list, list[0] … list[11]
81. Sorting
• Definition is discussed already in previous
slides.. See data structure operations types
82. Bubble Sort
• The technique we use is called “Bubble Sort”
because the bigger value gradually bubbles
their way up to the top of array like air bubble
rising in water, while the small values sink to
the bottom of array.
83.
84. • Algorithm: (Bubble Sort) BUBBLE (DATA, n)
• Here DATA is an Array with N elements. This algorithm sorts
the
• elements in DATA.
• 1. for(pass=n; pass>=1; pass--)
• 2. for(i=1; i<=pass; i++)
• 3. If DATA[i]>DATA[i+1], then:
• Interchange DATA[i] and DATA[i+1].
• [End of If Structure.]
• [End of inner loop.]
• [End of Step 1 outer loop.]
• 4. Exit.
85. C++ PROGRAMM FOR BUBBLE SORT
• #include<iostream>
• #include<conio.h>
• using namespace std;
• main()
• {
• int pass,n,i,temp;
• int a[10];
• cout<<"PROGRAM FOR BUBBLE SORT";
• cout<<"Enter size of array which is less than 10";
• cin>>n;
• for(i=1; i<=n; i++)
• {
• cin>>a[i];
• }
•
87. Insertion Sort
• Sorting method in which algorithm scan a
whole list one by one and in each iteration the
algorithm place each number to its correct
position.
91. See example animated example at
• http://courses.cs.vt.edu/csonline/Algorithms/
Lessons/InsertionCardSort/insertioncardsort.s
wf
92. STACKS
• It is an ordered group of homogeneous items
of elements. Elements are added to and
removed from the top of the stack (the most
recently added items are at the top of the
stack). The last element to be added is the
first to be removed (LIFO: Last In, First Out).
93.
94. • A stack is a list of elements in which an
element may be inserted or deleted only at
• one end, called TOP of the stack. The
elements are removed in reverse order of
that in which they were inserted into the
stack.
95. • Basic operations:
• These are two basic operations associated
with stack:
• Push() is the term used to insert/add an
element into a stack.
• Pop() is the term used to delete/remove an
element from a stack.
96.
97. Stack push and pop program
• #include<iostream>
• #include<conio.h>
• using namespace std;
• main()
• {
• int s[10], i,j,n;
• int top=0;
98. • do
• {
• cin>>j;
• s[top+1]=j;
• for(j=top+1; j>=1;j--)
• cout<<s[j]<<endl;
• top++;
• cout<<"do you want to process more
y/n"<<endl;
100. Queue
• A queue is a linear list of elements in which deletion
can take place only at one end, called the front, and
insertions can take place only at the other end, called
• the rear. The term “front” and “rear” are used in
describing a linear list only when it
• is implemented as a queue.
• Queue is also called first-in-first-out (FIFO) lists. Since
the first element in a
• queue will be the first element out of the queue. In
other words, the order in which
• elements enters a queue is the order in which they
leave.
101. • Primary queue operations:
• Enqueue: insert an element at the rear of the
queue.
• Dequeue: remove an element from the front
of the queue.
107. 107
Deques
• A deque is a double-ended queue
• Insertions and deletions can occur at either
end
• Implementation is similar to that for queues
• Deques are not heavily used
• You should know what a deque is, but we
won’t explore them much further