0% found this document useful (0 votes)
20 views

LEC 1 Introduction

This document outlines the objectives, outcomes, information, and outlines of an electrical engineering course on data structures and algorithms. The course aims to combine fundamental data structures and algorithmic techniques to build complete algorithmic solutions. It will describe different implementations of data structures and algorithms based on application requirements, evaluate algorithms in terms of time and memory complexity, and have students build a mini-project using object-oriented programming for various data structure and algorithm applications.

Uploaded by

demro channel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
20 views

LEC 1 Introduction

This document outlines the objectives, outcomes, information, and outlines of an electrical engineering course on data structures and algorithms. The course aims to combine fundamental data structures and algorithmic techniques to build complete algorithmic solutions. It will describe different implementations of data structures and algorithms based on application requirements, evaluate algorithms in terms of time and memory complexity, and have students build a mini-project using object-oriented programming for various data structure and algorithm applications.

Uploaded by

demro channel
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 57

Benha University

Electrical Engineering Department Benha Faculty of Engineering


Course Objectives

Course Information

Outlines
Course Objectives
❖Combine fundamental data structures and algorithmic techniques in
building a complete algorithmic solution to a given problem.
Course Outcomes (COs)
Course Learning Outcomes
CLO1 Describe the different implementations of data structures and algorithms for
appropriate design decisions based on application data requirements.

evaluate algorithms and data structures in terms of time and memory


CLO2
complexity of basic operations.

CLO3 Build a Mini-project using OOP coding for different data structures and
algorithms applications.
Course Information
Additional Course Notes - Lecture Notes.
References:
- Armstrong Subero, "CODELESS DATA STRUCTURES AND
ALGORITHMS", ISBN-13 (electronic): 978-1-4842-5725-8,
2020.
Essential Books (Textbooks): S.Mohanty and P.Tripathy, "Data Structure and Algorithms -
Using C++, A Practical Implementation", Scrivener Publishing,
John Wiley & Sons,2021.

- Mark Allen Weiss, "Data Structures and Algorithm Analysis in


C++", Fourth Edition, Florida International University, ISBN-13:
Recommended Books: 978-0-13-284737-7, Pearson Education, 2014.

Grading:
Assessment Method Week Weighting of Asses.

Midterm Exam 8 20%

Experimental 10%
15
Oral Test & Reports 10%
Final Exam
16 60%
Total 100%
Outlines

1- Introduction to Programming
2- Introduction to Data Structure and Algorithm
3- A Brief Revision to C++
Programming

a program is a set of step by step instructions that directs the computer to do the
tasks you want it to algorithm and produce the results you want.
The Evolution of Programming Languages

A programming language is a formal constructed


language usedto write computerprograms.
 Assembly language (low level)
 Assembler: translates a program written in assembly
language into machine language

 High-levellanguages include Basic, C, C++, C#, and Java……


 Compiler: translates a program written in a high-level
language into machine language 7
What Is Programming and Program Development Life Cycle ?
Programming is a process of problem solving

Step 1: Analyze the problem


Outline the problem and its requirements
Design steps (algorithm) to solve the problem

Step 2: Implement the algorithm


Analyze the problem
in code verify that the algorithm work

Understand problem
Step 3: Maintenance
requirements
Use and modify the program if there is a problem Does program require user
If the problem is complex, divide it into sub-problems interaction?
Analyze each sub-problem as above Does program manipulate
data? Algorithm:

ALGORITHM Step-by-step problem-solving process What is the output?


The Problem Analysis–Coding–
Execution Cycle
➢ Run code through compiler Problem Analysis
 If compiler generates Using Any
Programmig
errors Language Algorithm Design

Look at code and remove errors Run


code again through compiler Coding

➢ If there are no Complier


Errors
Translate Code To
syntax errors Machine
Language Execution
Compiler generates equivalent Errors
machine code
Get Results
9
A data structure

The data structure is a way that specifies how to organize and manipulate
the data. It also defines the relationship between them. Data Structures
are the central part of many computer science algorithms as they enable
the programmers to handle the data in an efficient way

◼We don’t want only to store data, we need to process it efficiently!

◼As algorithms field is all about efficiency,


Data Structures and Algorithms are highly related!
DS Usually studied after programming and before or with algorithms
From a purpose to another, we may arrange data in different ways
That is, it is NOT one way to implement a data structure
Facebook data ,liame ,eman( sliated tnuocca ruoY :
password), your friends list, your images and videos, your
posts (replies, likes), Ads, groups, attached files …etc

Dictionary ot woH ?sdrow fo sdnasuoht ynam era erehT :


store the words? Sorted? In an array? What about common
Prefix between words (autopilot, autobiography ,
automobile)? Search for a word that starts with “univ“.

E.g. If a storm hits specific list of locations, how many


homes will face a power outage?

E.g. We are in a war ,and want to destroy the minimum


number of bridges in a city to disconnect 2 points of our enemy ?
Google mapsog ot tnaw I :
From School to Home? From
Cairo to London? How to store
these
locations/path? How
to efficiently find the path
between two points

Think about the google maps example

◼We have lots of details about the locations


and paths
◼Variety of transportation options
◼Transportations availability vs date/time
◼Roads that get closed temporarily
◼New added roads. Changed roads.
Removed roads
Data inside a data structure
data structure may contains other Dses
Complex functionalities = Complex Data Structures
Ex :What is inside the Facebook account DS:

◼Your Name (Array of chars(


◼Your Email / Address / Password (Each is Array of chars(
◼Your Age (integer(

◼Your Albums (Array of Albums(


What is an album! Array of photos!
What is photo? Date, Location and Image
What is an image !2D Array of pixels!
A pixel ?3 integers (red, green, blue(
Your Posts (Array of Posts(
What is a post!
◼What is inside the post DS ?

Post text (Array of char(


Replies on post (Array of replies(
What is a reply? Author Facebook Account ID +
Array of chars for his text reply?
But this is sequential array of replies! Very simple.
What if we want to allow reply on reply on reply?
More complex way of organizing your data needed!
Data Structures tradeoffs

◼As mentioned, one might implement several data structures


over the same data

◼However, one data structure might make some operations


so fast, while others are so slow

◼One must understand what is requested to achieve a


proper tradeoffs

Your deep understanding for the requirements + your


design skills are the key
◼Specifically, we have 2 measures: Time and Memory
◼A real time application usually emphasize the time
concern (Think in games(

◼Mobile Applications

◼Your feelings when the browser consume your machine


available RAM ?or slow when processing large data?
Logical and Physical Views

What is an email service?


◼An online address
◼You create the account
◼Then, you can send/receive emails
◼This is a logical view

What are email service providers?


◼They providers implement such service in their own ways
◼Examples; Gmail, Yahoo, Hotmail
◼Many people might be fan of the implementation
efficiency of gmail. This is a physical view
What is a queue?
◼A data structure to enqueue and dequeue items respecting FIFO
principle
◼This is a logical view (Abstract Data Type(

How a queue is implemented?

◼Using an array internally of items


◼Index to know where we are
◼Add element put in the array, index++
◼Remove element, do index—
◼Can we implement in different ways? SURE
◼might be implemented using linked list or array-based list
Abstract Data Type
An abstract data type, sometimes abbreviated ADT, it is a logical description
of how we view the data and the operations that are allowed without regard
to how they were implemented.

The implementation of an abstract data type, often Referred to as a data structure,


will require that we Provide a physical view of the data using some Collection of
programming constructs and primitive Data types.
The common data structures

❖People noticed some data structures that repeat much


So, instead of each one keep reimplementing them
They are already implemented for you to use

❖Hence, in real life projects, you build more complex data


structures based on the common data structures

❖Through this course ,we learn how to build a data structure


Hence, we learn how to use them the commons properly

Why learn them if already implemented? Read above


again slowely.
Classification of Data Structure
Data structure

Primitive DS Non-Primitive DS

Integer Float Character Pointer

A primitive data structure is generally a basic structure that is usually built into the
language, such as an Integer, Floating-point number, Character constants, string constants,
pointers etc, fall in this category.
 There are more sophisticated DS Non-Primitive DS
 The non-primitive data
structures emphasize on
structuring of a group of
homogeneous (same type) or Linear List Non-Linear List
heterogeneous (different
type) data items.
 A non-primitive data
structure is built out of Queue
primitive data structures Array Link List Graph Trees
linked together in meaningful
ways. Stack
A linear data-strucutre has sequentially arranged Non-Linear Data Structure: The Non-linear data
data items. The next time can be located in structure does not form a sequence i.e. each item or
the next memory address. It is stored and element is connected with two or more other items
accessed in a sequential manner. Array and in a non-linear arrangement. The data elements are
list are example of linear data structure. not arranged in the sequential structure.
Array

Linked List

Queue Stack
Tree

There are many, but we named a few. We’ll learn these


data structures in great detail!
Basic Data structures
◼We also use them much in reality
Advanced Data
Examples: Lists, Stack, Queues and Trees structures
◼ex: Queue Data Structure: You in restaurant
and people come to ask for food orders . ◼These were more critical or
People have a fair concept First come complex scenarios are needed
First Out (FIFO).A queue data structure ◼Popular ones in courses are
just implement that concepts. Heaps, Hash tables and Red
Black trees
In programming, operating system jobs need a
queue
T H I N K F A S T

Algorithms
How to implement?
A normal calculator program. Direct translation for requirements can do it!
Remember to respect math: 2+1*5 = 7 NOT 15
Given 1000 integers, find how many 3 numbers with sum 400?
 We can do 3 loops and try every 3 numbers!
 1000000000 operations! Too much Computations!

Given 1000 integers, sort them?


 nothing direct in mind...I need to think more!

Given airport locations and cost of every direct flight, find flight
from cairo to newyork with the minimum cost?
 ..how to represent airports relations!
Facebook site has 1.4 Billion users, please suggest to mostafa
all new friends from them, where there is exactly 2 friends
between mostafa and each of a new friend?

 For every user in the system


 Count intersection of mostafa users and this user
 If count == 2, we suggest this friend
 ...too many billion operations
 ..system memory can’t hold even all of that!
 Our solution performance is too bad!
Performance
In real life applications, we care with many factors
 E.g. Usability, Security, Maintainability, Reliability...etc

One of the major factors is the performance


A memory and time efficient applications are desirable features.
 Imagine if facebook is a slow application!

This is where algorithms field arises!


 Computational solution that is efficient time and memory
High performance real life apps
Algorithms
 Algorithm: A sequence of steps to solve a Computational problem.
 Decision - Search - Counting, Optimization ... Problems

 Nature of Computational problem


 Much of computations
 Direct requirements translation is not do able..must think
 Or doable, but direct idea is so slow..or takes much memory….we need a
more efficient solution
Algorithms Analysis
 Given an algorithm, we need to
 1) Prove its Correctness
 2) Measure time efficiency
 3) Measure memory efficiency

 Steps 2 and 3 allow us to compare algorithms


 Fall in complementary area: Computational Complexity

 An example of sorting algorithms


 Selection sort, ordersN numbers using N*N operations
 Quicksort, orders N numbers using N*log2N operations
 Then Quicksort is faster...and better algorithm
Programming Prerequisites
Forthe majority of algorithms you need basic programming
concepts
 Data types and variables
 Selection, Repetition, Functions, Arrays, Struct (class)
Yes just basics, but you need to be clever
For little algorithms, a data structure course is needed
Increment and Decrement Operators(prefix and postfix)

 Increment operator: increment variable by 1


Pre-increment: ++ variable
Post-increment: variable++

 Decrement operator: decrement variable by 1


Pre-decrement: --variable
Post-decrement: variable --

 Examples :
++K , K++ → k= K+1
---K , K-- → K= K-1

36
 When ++ (or – –) is used before the variable name, the
computer first increments (or decrements) the value of the
variable and then uses its new value to evaluate the expression.

 When ++ (or – –) is used after the variable name, the computer


uses the current value of the variable to evaluate the expression,
and then it increments (or decrements) the value of the variable.

 There is a difference between the following

x = 1; x = 1;
Cout << x++; Cout << ++x;

37
special assignment statements

X +=2 ; means x = x + 2;
x *=y; means x = x * y;
x /=y; means x = x / y;

Int v=0;
Cout<<v++;
V++;
Cout<< v--;
--v;
Cout<< v++;
38
Functions

 Experience has shown that the best way to develop and maintain a large program is
to construct it from smaller pieces or modules, each of which is more manageable
than the original program.

 A Function : is a self-contained block of statements that perform a specific task.


 using a function is something like hiring a person to do a specific job for you.
In Real Life
In Programming

Task 4
Task 1
Function ( )
Function ( )

Task 3
Task 2

Function ( ) Function ( )
40
Function Definition
Parameter
Data_type function-name( parameter ) It is input to the function. It
is Optional
{
Lines of code to be
In return function
executed It Is the data type for the returned value
… from the function to the calling program. if
no returned value expected , we use Void
…… function.
(Body)
RETURN ;
} Float main(float v1, float v2) Void sw(int& x1,int & x2)
{ {
Float c= v1+v2; Int x3 =x1;
Return c; X1=x2;
41
} X2=x3;}
Arrays
 Array : is a collection of fixed number of elements, where in all of elements
have same data type.
 Array Basics:
 Consecutive group of memory locations that all have the same type.
 The collection of data is indexed, or numbered, and at starts at 0 and
The highest element index is one less than the total number of elements
in the array.
 One-dimensional array:

 elements are arranged in list form.

 Multi-dimensional array:

 elements are arranged in tabular form.


Syntax for declaring a one-dimensional array:

Datatype ArrayName [ArraySize] ;


arr

ArraySize: any positive integer or constant variable.

• Example:
int arr[5];

• Example: const int size = 5 ;


int arr[size];

43
Recall that arrays go from 0 to size– 1
Array Initialization
 Consider the declaration

int array[10]; //array of size 10

 After declaring the array you can use the For .. Loop to initialize it with values
submmited by the user.
Example:
for (int i = 0; i < 10; i++)
cin >> array[i];

➢ In this case, it is not necessary to specify the size of the array


Size determined by the number of initial values in the braces

int Items[] = {12, 32, 16, 23, 45};


Two Dimensional Array
 Used when data is provided in a table form.
 For Example , to store 4 Marks for 6 students.
M1 M2 M3 M4

Student 1

Student 2

Student 3

Student 4

Student 5

Student 6

 declaration
Datatype ArrayName [ Rows] [Columns] ;
Float array [6] [4] ;
declaration
 After declaring the array you can use the For .. Loop to initialize it
with values submmited by the user.

Using 2 nested for loops to access array elements:


for (int row = 0; row < 6; row++)
for (int col = 0; col < 4; col++)
cin >> array[ row ][col];

46
Int main() Int main()
Void add ( int a[3][4] )
{ {
Const int b=5; {
Const int row =3, col=4;
Int cv[b]; Int sum =0;
Int x[row][col];
Int sum =0;
For (int i=0; i<b; i++) For (int i=0; i<3; i++)
{ For (int i=0; i<row; i++)
For (int j=0; j<4; j++)
Cout<< “enter the values”<< i<<endl; For (int j=0; j<col; j++)
Cin>>cv[i]; {
{
} Sum+= a[i][j];
Cin>> x[i][j];
}
For (int i=0; i< b; i++) }
{
Sum = sum + cv[i]; Add(x);
} Cout<< “the sum is
Return 0;
“<<sum;
}
Cout<< sum << endl; Cout<< sum/ 12;
Return 0; }
}
Structure struct Employee
{
 A Structure is a collection of related data items, possibly of int emp_no ;
different types. string fname ;
string lname;
 A structure type in C++ is called struct. float salary;
float bonus ;
 In contrast, array is homogeneous since it can contain only data of
float total_salary;
the same type. };

int main ()
For Example : To store an Employee data like {
Employee emp1;
( emp_no , fname , lname , salary , bonus , total_salary ); emp1.emp_no = 12;
emp1.fname="Ahmed";
emp1.lname="Ali";
To Access the Memebers of the struct , use the . Operator emp1.salary=3000;
emp1.bonus=500;
emp1.total_salary=
emp1.salary +
emp1.bonus;
}
48
Classes in C++
 A class definition begins with
the keyword class. class class_name
 The body of the class is
{ private members or
private: methods
contained within a set of braces, { }; …
(notice the semi-colon). …

public: Public members or methods
 Within the body, the keywords private: …
and public: specify the access level …

of the members of the class. };
the default is private.

 Usually, the data members of a class are declared in the private:


section of the class and the member functions are in public:
Class point Int main()
{ {
Private: Point p1;
Float x1;
Float x2;
P1.show();
Char op; Return 0;
Public: }
Point()
{
X1= 0.0f;
X2= 1.0 f;
Op=‘+’;
}

Void show()
{
Cout<<x1<< “ “<<x2<<endl;
}
};
Pointers
One of the simplest ideas in C++, but one which most students have a problem
with is a pointer

 Every variable is stored somewhere in memory


 That address is an integer, so why can’t we store an address in a variable?

we have to indicate what it is pointing to:

int *ptr; // a pointer to an integer


// the address of the integer variable 'ptr'
First we must get the address of a variable
This is done with the & operator . We can even print the addresses:

int m = 5; // m is an int storing 5


int *ptr; // a pointer to an int
ptr = &m; // assign to ptr the
// address of m
cout << ptr << endl;

prints 0xffffd352, a 32-bit number


The computer uses 32-bit addresses
We have pointers: we would now like to manipulate what is stored at that
address

We can access/modify what is stored at that memory location by using


the * operator (dereference)

int m = 5;
int *ptr;
ptr = &m;
cout << *ptr << endl; // prints 5
Similarly, we can modify values stored at an address:

int m = 5;
int *ptr;
ptr = &m;

*ptr = 3; // store 3 at that memory location


cout << m << endl; // prints 3
Conclusion
◼ Algorithm is a step by step procedure, which defines a set
of instructions to be executed in certain order to get the
desired output.
◼ the data structure is the way of organizing the data with
their logical relationship retained.

◼ To develop a program of an algorithm, we should select an


appropriate data structure for that algorithm.

Therefore algorithm and its associated data structures form a


program.
The Need for Data Structures

❑ Goal: to organize data

❑ Criteria: to facilitate efficient


▪ storage of data
▪ retrieval of data

▪ Design Issue:
▪ select and design appropriate data types
(This is the main motivation to learn and understand
data structures)

You might also like