Algorithm Design & Data Structures

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 85

ALGORITHM

DESIGN & DATA


STRUCTURES
MAXMILLAN GIYANE
Midlands State University
Chairperson - Computer Science
0773260927
[email protected]
OBJECTIVES
 Todescribe algorithms using pseudo codes and
flowcharts.
 Toexplain searching and sorting algorithms in problem
solving.
INTRODUCTION

Intelligence is one of the key


characteristics which differentiate a
human being from other living creatures on
the earth.
Basic intelligence covers day to day
problem solving and making strategies to
handle different situations which keep
arising in day to day life.
E.g. Cooking Sadza

Duringthe process of solving any


problem, one tries to find the
necessary steps to be taken in a
sequence.
PROBLEM SOLVING
 Can you think of a day in your life which goes without
problem solving?
 In our life we are bound to solve problems.
 Itcan be said that whatever activity a human being or
machine do for achieving a specified objective comes
under problem solving.
 E.g.Watching TV, Telling someone the time of the day,
Budgeting etc
 Now,broadly we can say that a problem is a kind of
barrier to achieve something and problem solving is a
process to get that barrier removed by performing
some sequence of activities.
 Hereit is necessary to mention that all the problems in
the world can not be solved.

 Thereare some problems which have no solution and


these problems are called Open Problems
 Ifyou can solve a given problem then you can also
write an algorithm for it.

WHAT IS AN ALGORITHM?

1. A sequence of activities to be processed for getting


desired output from a given input.
2. A formula or set of steps for solving a particular
problem.
3. It is a step-by-step procedure to solve a given
problem
4. It is a series of steps that can be followed to
complete a task.

 NOTE: There may be more than one way to solve


a problem, so there may be more than one
algorithm for a problem.
Example of an Algorithm

Problem : Find the area of a Circle of radius r.


 Inputs to the algorithm:
Radius r of the Circle.
 Expected output:
Area of the Circle
Algorithm:

 Step1: Start
 Step2: Read\input the Radius r of the Circle
 Step3: Area PI*r*r // calculation of
area
 Step4: Print Area
 Step5: End
Write an algorithm to read two numbers and find their
sum.

 Inputs to the algorithm:


First num1.
Second num2.
Expected output:
 Sum of the two numbers.
Algorithm:
 Step1: Start

 Step2: Read\input the first num1.

 Step3: Read\input the second num2.

 Step4: Sum num1+num2 // calculation of sum

 Step5: Print Sum

 Step6: End
 Algorithms
can be designed though the use of flowcharts
or pseudocode.

FLOWCHART
 Theflowchart is a diagram which visually presents the flow
of data through processing systems.

 This
means by seeing a flow chart one can know the
operations performed and the sequence of these
operations in a system.
A flowchart, will describe the operations (and in what
sequence) required to solve a given problem.

Flowchart Symbols
 Thebasic symbols commonly used in flowcharting of
assembly language Programs are: Terminal, Process,
input/output, Decision,Connector and Predefined
Process.
SYMBOL NAME FUNCTION
Process Indicates any type of internal operation
inside the Processor or Memory
Input/output Used for any Input / Output (I/O)
operation. Indicates that the computer is
to obtain data or output results
Decision Used to ask a question that can be
answered in a binary format (Yes/No,
True/False)
Connector Allows the flowchart to be drawn without
intersecting lines or without a reverse
flow
Predefined process Used to invoke a subroutine or Terminal
an Interrupt program.
Terminal Indicates the starting or ending of the
program, process, or interrupt program

Flow lines Shows direction of flow.


Find the area of a circle of radius r.
START

READ r

AREA = 3.14*r*r

PRINT AREA

END
Flowchart for an algorithm which gets two
numbers and prints sum of their value

START

READ A, B

C A+B

PRINT C

END
Problem: Design an algorithm and the corresponding
flowchart for adding the 5 test scores:
Algorithm
1. Start
2. Sum = 0
3. Get a value
4. sum = sum + value
5. Go to step 3 to get next Value
6. Output the sum
7. Stop
Start

Sum = 0

Get a Value

Sum= Sum + Value

Output Sum

End
PSEUDOCODE
 Pseudocode is one of the tools that can be used to
write a preliminary plan that can be developed into
a computer program.
 Pseudocode is a generic way of describing an
Algorithm without use of any specific programming
language syntax.
 Pseudocode is an algorithmic tool that express a
solution to a problem using simple English like
statements that are closer to a programming
language.
CONTROL STRUCTURES OR LOGICAL STRUCTURES

 Thekey to better algorithm design and thus to


programming lies in limiting the control structure to only
three constructs. These are illustrated as follows:

The sequence structure


 Thesequence structure is a case where the steps in an
algorithm are constructed in such a way that, no
condition step is required.
 The sequence structure is the logical equivalent of a
straight line.
For example, suppose you are required to design an algorithm for
finding the average of six numbers, and the sum of the numbers is
given. The pseudocode will be as follows

 Start
 Get the sum
 Average = sum / 6
 Output the average
 Stop

 The corresponding flowchart will appear as follows:


START

GET THE SUM

AVERAGE = SUM/6

OUTPUT AVERAGE

END
Decision Structure or Selection Structure
 Thedecision structure or mostly commonly known as a
selection structure, is case where in the algorithm,
one has to make a choice of two alternatives by
making decision depending on a given condition.

 Selection
structures are also called case selection
structures when there are two or more alternatives
to choose from.
 In pseudocode form we get

If condition is true
Then do task A
else
Do Task-B
 The program is to input a examination mark and test it
for the award of a grade. The mark is a whole number
between 1 and 100. Grades are awarded according to
the following criteria:
>= 80 Distinction
>= 60 Merit
>= 50 Pass
< 49 fail
 The pseudo-code is

Use variables: mark of type integer


If mark >= 80 display “distinction”
If mark >= 60 and mark < 80 display “merit”
If mark >= 50 and mark < 60 display “pass”
If mark < 49 display “fail”
The case statement

 Repeating the if … else statements a number of times


can be somewhat confusing.
 An alternative method provided in a number of languages
is to use a selector determined by the alternative
conditions that are needed.
 In our pseudo-code, this will be called a case statement.
 The following program segment outputs a message to the
monitor screen describing the insurance available
according to a category input by the user.
Use variables: category of type character
Display “input category”
Accept category
If category = U
Display “insurance is not available”
Else
If category = A then
Display “insurance is double”
Else
If category = B then
Display “insurance is normal”
Else
If category = M then
Display “insurance is medically dependent”
Else
Display “entry invalid”
This can be expressed in a case statement as follows:
Use variables: category of type character
Display “input category”
Accept category
DO case of category
CASE category = U
Display “insurance not available”
CASE category = A
Display “insurance is double”
CASE category = B
Display “insurance is normal”
CASE category = M
Display “insurance is medically dependent”
OTHERWISE
Display “entry is invalid”
ENDCASE
Repetition or Iteration Structure

A third structure causes the certain steps to be repeated.


The Repetition structure can be
implemented using
• Repeat Until Loop
• The While Loop
• The For Loop
 Anyprogram instruction that repeats some statement or
sequence of statements a number of times is called an
iteration or a loop.
 The commands used to create iterations or loops are all
based on logical tests. There three constructs for
iterations or loops in our pseudocode.
The Repeat Until loop.
The syntax is
REPEAT
A statement or block of statements
UNTIL a true condition

A program segment repeatedly asks for entry of a number in the range 1 to


100 until a valid number is entered.

REPEAT
DISPLAY “Enter a number between 1 and 100”
ACCEPT number
UNTIL number < 1 OR number > 100
Note
Steps for solving a programing task
1. Problem analysis – separating the known from the
wanted and identifying any formulae and conditions
that are involved in solving the problem
2. Program designing-
a. Algorithms – presenting the sequence of steps one
should follow in solving the problem. Algorithms
are written in the designer’s language of choice.
b. Flowcharts – presenting the sequence of steps one
should follow in solving the problem using known
standard symbols.
c. Pseudocodes – presenting the sequence of steps one should
follow In solving the problem. Pseudocodes use a language
which is biased towards the programming language to be
used to implement the program.
3. Coding
4. Debbuging
a. Dry running – a check of the logic and coding of a
computer program in which the program’s operations are
followed and the results of each step are written down,
before the program is run.
b. Trace table - a technique used to test algorithms, in
order to make sure that no logical errors occur whilst the
5. Documentation

Internal & user manual

6. Deployment - installation
Dry run

Dry run is a process of selecting appropriate test


data and execute the algorithm by hand until the
program terminates.
When performing a dry run, the state of the
variables used is updated after each program
instruction is carried out.
The state of the variable is stored in a trace table
Trace Tables

A trace table is a rectangular array where the column heading


records the names of all the variables used in the algorithm and
the rows records the state of the variables after every instruction
executes.
Problem. Use trace table to test the accuracy of the logic of the
following pseudocode :
Sum = 0
Get a value
sum = sum + value
Go to step 2 to get next Value
Output the sum

Use 1,2,3 as input test data


Sum Value Sum Value
Sum Value Sum Value
0 0 1 0 1
0 1
1 1 2

Sum Value Sum Value


Sum Value
0 1 0 1
0 1
1 2 1 2
1 2
3 3 3
3 3
6
 The logic is correct since it evaluates to 6
STANDARD
ALGORITHMS
STANDARD ALGORITHMS
Since computers were created, users have devised programs,
many of which, in part, needed to do the same thing.
 As a result, standard algorithms have evolved and been
adopted in many programs.
Two types of algorithms that are often used are searches and
sorts.
1. Searches enable a data set to be examined and a specific item
to be found.
2. Sorts enable a data set to be sorted into specific order.
SEARCHING
ALGORITHMS
Searching: the process of finding the desired element in a
set of items.
The selected element is called a “target”.
Searching can be done using two methods:

1. Linear/Sequential

2. Binary/Half-interval.
LINEAR SEARCH
LINEAR SEARCH
A linear search is the simplest method of searching
a data set.
Starting at the beginning of the data set, each item
of data is examined until a match is made.
Thus searching is sequential.
Once the item is found, the search ends.
If there is no match, the algorithm must deal with
this (thus stopping the search and alerting the user).
Algorithm for Linear Search
1. Find out the length of the data set.
2. Set counter to 0.
3. Examine value held in the list at the counter position.
4. Check to see if the value at that position matches the value
searched for.
5. If it matches, the value is found. Send a message and end the
search.
6. If not, increment the counter by 1 and go back to step 3 until
there are no more items to search.
7. If all the items have been checked and no match is found, send a
message.
Example
Suppose we were to search for the value 8
in this list.
The search would start at position 0 and
check the value held there, in this case 2.
2 does not match 8, so we move on to the
next position.
Search ends at position 5 where the value
of 8 is found.
BINARY SEARCH
Binary Search

A binary search is an efficient method of


searching an ordered list.
It will not work on a list that has not been
sorted first.
Searches for an element in a sorted array
Algorithm for binary search
A written description of a binary search algorithm is:

1. Start by setting the counter to the middle position in the list.


2. If the value held there is a match, the search ends and a message
is sent.
3. If the value at the midpoint is less than the value to be found, the
list is divided in half, the lower half of the list is ignored and the
search keeps to the upper half of the list.
4. Otherwise, if the value at the midpoint is greater than the value
to be found, the upper half of the list is ignored and the search
keeps to the lower half of the list.
5. The search moves to the midpoint of the remaining items. Steps
two to four continue until a match is made or there are no more
items to be found and a message is sent.
Binary search example
Consider searching for the value 11.
The midpoint is found by adding the lowest position to the highest position
and dividing by 2.
 Highest position (8) + lowest position (0) = 8
 8/2 = 4
NOTE - if the answer is a decimal, round up. For example, 3.5 becomes 4.
An alternative is to round down, but be consistent.
Check at position 4, which has the value 7.
7 is less than 11, so the bottom half of the list - including the midpoint - is
discarded.
Binary search (cont)
The new lowest position is 5.
 Highest position (8) + lowest position (5)
= 13
 13/2 = 6.5, which rounds up to 7
Check at position 7, which has the value 14.
14 is greater than 11, so the top half of the
list (including the midpoint) is discarded.
Binary search (cont)
The new highest position is 6.
 Highest position (6) + lowest position (5) = 11
 11/2 = 5.5, which rounds up to 6
Check at position 6.
The value held at position 6 is 11 - a match. The
search ends.
Alternatively

 1. define start (s) and end (e)


 2. find the middle index (m) , thus m=
 3. Find where the element is placed with respect to the middle index (m)
thus, if A[m] < element, search to the right of the middle element.
Start = m+1, end = end.

If A[m] > element, search to the left of the middle element


start= start, end = end-1

if A[m]=element, FOUND, return index

If start=end, I element left


A[m]!=element., NOT FOUND
Summary
• In a linear search, each element in the list is searched one after
the other in a sequential manner until it is found in the list.
• A binary search, on the other hand, finds the list’s middle
element recursively until the middle element matches a
searched element.
• Linear search can be suitable for searching over an unsorted
array. whereas, Elements in the array need to be in sorted order
for binary search.
• The binary search algorithm uses the divide-and-conquer
approach, it does not scan every element in the list. Hence, It is
the best search algorithm.
SORTING
ALGORITHMS
Sorting
1. arranging items into a particular order
2. grouping similar items together

Sorting algorithms are a set of instructions that take an array


or list as an input and arrange the items into a particular order.
SORTING ALGORITHMS INCLUDE:

1. Bubble sort
2. Quick sort
3. Merge sort
4. Selection Sort
5. Insertion Sort
6. Merge Sort
BUBBLE SORT
Bubble sort
A bubble sort is the simplest sorting algorithm that works
by repeatedly swapping the adjacent elements if they are in
the wrong order.
Although it is simple to use, it is primarily used as an
educational tool because the performance of bubble sort is poor in
the real world. It is not suitable for large data sets.
However, it is an inefficient sort for anything but a small list
because of the number of comparisons required.
Bubble sort
Algorithm for bubble sort
1. Start at the beginning of the list.
2. Compare the first value in the list with the next one up. If the
first value is bigger, swap the positions of the two values.
3. Move to the second value in the list. Again, compare this
value with the next and swap if the value is bigger.
4. Keep going until the there are no more items to compare.
Note - the last item checked in the list is now sorted, so
ignore this next time.
5. Go back to the start of the list.
Example
 To understand the working of bubble sort algorithm, let's take an unsorted array.
 Let the elements of array are –
Quick sort
The quick sort algorithm is a faster and highly efficient sorting
algorithm.

This algorithm follows the divide and conquer approach.

Divide and conquer is a technique of breaking down the


algorithms into subproblems, then solving the subproblems, and
combining the results back together to solve the original problem.
Quick sort
Algorithm for quick sort
1. Pick - Select an element.
2. Divide - Split the problem set, move smaller parts
to the left of the pivot and larger items to the
right.
3. Repeat and combine – repeat the steps and
combine the arrays that have previously been
sorted.
It is a faster and highly efficient sorting algorithm. This algorithm follows
the divide and conquer approach. Divide and conquer is a technique of
breaking down the algorithms into subproblems, then solving the
subproblems, and combining the results back together to solve the original
problem.

Divide: In Divide, first pick a pivot element. After that, partition or


rearrange the array into two sub-arrays such that each element in the left
sub-array is less than or equal to the pivot element and each element in the
right sub-array is larger than the pivot element.

Conquer: Recursively, sort two subarrays with Quicksort.

Combine: Combine the already sorted array.


Quicksort picks an element as pivot, and then it
partitions the given array around the picked pivot
element.
In quick sort, a large array is divided into two arrays
in which one holds values that are smaller than the
specified value (Pivot), and another array holds the
values that are greater than the pivot.
After that, left and right sub-arrays are also partitioned
using the same approach.
It will continue until the single element remains in the
sub-array.
Choosing the pivot
Picking a good pivot is necessary for the fast
implementation of quicksort.
However, it is typical to determine a good pivot.
Some of the ways of choosing a pivot are as follows
-
•Pivot can be random, i.e. select the random pivot
from the given array.
•Pivot can either be the rightmost element or the
leftmost element of the given array.
•Select median as the pivot element.
Data Structure

is a way to store and organize data so


that it can be used efficiently

is a way of storing data in a computer so


that it can be used efficiently and it will
allow the most efficient algorithm to be
used.

The organized collection of data


Data Structures Classification
Types of Data Structures
There are two types of data
structures:
Primitive data structure
Non-primitive data
structure
Non
Primitive Data Structures
1.Primitive Data Structures are the data structures
consisting of the numbers and the characters that come in-
built into programs.
2.These data structures can be manipulated or operated
directly by machine-level instructions.
3.Basic data types like Integer, Float, Character,
and Boolean come under the Primitive Data Structures.
4.These data types are also called Simple data types, as they
contain characters that can't be divided further
Non-Primitive Data Structures
1.Non-Primitive Data Structures are those data structures
derived from Primitive Data Structures.
2.These data structures can't be manipulated or operated
directly by machine-level instructions.
3.The focus of these data structures is on forming a set of
data elements that is either homogeneous (same data type)
or heterogeneous (different data types).
4.Based on the structure and arrangement of data, we can
divide these data structures into two sub-categories -
1.Linear Data Structures
2.Non-Linear Data Structures
Thank You
Siyabonga
Tatenda
Asante Sana

You might also like