algo_chap_3
algo_chap_3
2023/2024
2
1
Arrays
• The simple answer is to create for each student a variable that represents his average,
then compute the average,
• Or, we can use a loop to input the students' means and directly compute the sum of
averages, and after we finish entering the scores we can assess the overall average.
The issues
• We need something to process and assess a large amount of data efficiently, more
precisely a data structure to represent a group of information with the same type.
The Arrays
• An Array is a data structure that stores a collection of items of the same type. It is one of
the most fundamental and widely used data structures in programming. Arrays are
typically implemented as contiguous blocks of memory, which means that the elements
of an Array are stored next to each other in memory. This makes it easy to access and
manipulate individual elements of an Array.
Example :myArray: Array[1..5] of Integer; would create an Array named myArray that can store 5 integer values with
indices ranging from 1 to 5.
Address 100 104 108 112 116
The Value
MyArray 13 -5 13 18 0 of the
Alternative declaration: Elements
Indices (index) 1 2 3 4 5
myArray: Array[Size] of DataType;
Example :myArray: Array[5] of Integer; would create an Array named myArray that can store 5 integer values with
indices ranging from 1 to 5.
7
Exercise 1
• You are given an Array of 100 integers. Write an algorithm that implements a linear search to find a
specified target value within the Array. The algorithm should return the index of the target value
Algorithm LinearSearchFixedArray;
const
N = 100;// to help us specify the size of an Array using a constant // Perform linear search
var I←1;
targetValue, I, index: Integer; While(I<= N and targetFound <> True ) do
myArray: Array[1..N] of Integer; // another way to declare an Array if myArray[i] = targetValue then
targetFound: Boolean; index ←I; // set the index where the target value is found
begin targetFound ← True; // Set targetFound to True if the target value is found
// Input elements of the Array EIF;
write('Enter the elements of the Array:'); I++;
for i ← 1 to N do Done;
begin If (targetFound) then
Read(myArray[i]); write(“The target”,targetValue,”is found at the position”,index);
done; Else write(“The target”,targetValue,”doesn’t exist”); EIF;
// Ask the user for the target value end.
write('Enter the target value to search for: ');
read(targetValue);
targetFound ← False; // Initialize targetFound as False, the target doesn’t exist in our Arrays,
11
Complexity
• In computer science and algorithm analysis, "complexity" generally refers to the analysis of an algorithm's efficiency
and resource usage. There are primarily two types of complexity: time complexity and space complexity.
• Time Complexity: evaluates the amount of time an algorithm takes to complete its task, It is measured in terms of the
number of basic operations (comparisons, assignments, etc.) an algorithm performs to solve a problem. Time
complexity is usually denoted using "big O" notation and provides an upper bound on the growth rate of an algorithm
as the input size increases.
• Analyzing complexity is crucial for understanding how algorithms behave with larger inputs. It helps in choosing the
most appropriate algorithm for a particular problem based on the trade-off between time and space efficiency. Lower
time complexity generally means faster execution, while lower space complexity implies efficient use of memory.
• "Big O" notation is widely used to express both time and space complexities. It represents the upper bound of the
growth rate of an algorithm. For instance, O(1) denotes constant time complexity (the algorithm's execution time
remains constant, regardless of the input size), O(n) signifies linear time complexity, O(log n) indicates logarithmic
time complexity, and so on.
• By assessing the complexity of algorithms, programmers and computer scientists can make informed decisions
regarding which algorithms to use based on the specific requirements of a problem, considering factors such as input
size, available memory, and desired execution speed.
14
Comparing the time complexities, binary search has a significantly better worst-case time complexity than linear
search for large datasets. Binary search's logarithmic time complexity makes it much more efficient for finding
elements in sorted Arrays compared to linear search, especially as the size of the dataset grows.
15
Exercise 2
• You are given an Array of 100 integers. Write an algorithm implementing a binary search to find a
specified target value within the Array. The algorithm should return the index of the target value
Algorithm BinarySearch;
const First ← 1;
N = 100;/ Last ←N;
var If (V >= myArray[FIrst] and V <= myArray[Last]) then
targetValue, First,Last, Mid: Integer; While(First<= Last and targetFound <> True ) do
myArray: Array[1..N] of Integer; Mid ←(First+Last) div 2;
targetFound: Boolean; if (myArray[Mid] = targetValue) then
begin targetFound ← True;
// Input elements of the Array Else if (myArray[Mid] < targetValue) First ← Mid+1;
write('Enter the elements of the Array:'); else Last ← Mid-1; EIF;
for i ← 1 to N do EIF;
begin Done;
Read(myArray[i]); EIF;
done; If (targetFound) then
// Ask the user for the target value write(“The target”,targetValue,”is found at the position”,Mid);
write('Enter the target value to search for:'); Else write(“The target”,targetValue,”doesn’t exist”); EIF;
read(targetValue); targetFound ← False; end.
16
2
Sorting Algorithms
What’s sorting ?
• Sorting, in the realm of computer science, refers to the process of Arranging elements or data in a specific order,
typically in either ascending or descending order based on a specified criterion. The primary goal of sorting is to
organize the data in a way that makes it easier to search, retrieve, and analyze.
• Here are definitions of a few popular sorting algorithms:
1. Bubble Sort: This algorithm compares adjacent elements in a list and swaps them if they are in the wrong order. It
continues to iterate through the list until no more swaps are needed.
2. Selection Sort: The selection sort algorithm divides the list into a sorted and an unsorted part. It repeatedly selects the
smallest (or largest, depending on the desired order) element from the unsorted portion and moves it to the sorted
part.
3. Insertion Sort Similar to how people sort playing cards in their hands, insertion sort builds the final sorted list one
item at a time. It takes an element from the list and places it in its correct position in the sorted portion.
4. Quick Sort: It’s a divide-and-conquer algorithm, quick sort picks an element as a pivot and partitions the Array
around the pivot, such that elements smaller than the pivot are on its left and larger elements are on the right. It then
recursively sorts the sub-Arrays.
18
In simple terms, the algorithm works by 'bubbling' the largest elements to the end of the list in each pass, gradually
sorting the list until no more swaps are required.
19
• For example, consider an Array with elements `[5, 3, 8, 2, 7]`. The Bubble Sort process might look something like this:
• The process continues until the entire Array is sorted in ascending order.
• This sorting method is quite intuitive but is less efficient compared to other sorting algorithms, especially for larger
datasets, due to its high time complexity, typically O(n^2) in the worst-case scenario.
20
[8, 3, 5, 1, 4]
1. Pass 1:
- Find the minimum element in the unsorted part (1).
- Swap it with the first element (8).
- Result: [1, 3, 5, 8, 4]
2. Pass 2:
- Find the minimum element in the remaining unsorted part (3). Swap it with the first element in the remaining unsorted part (8).
- Result: [1, 3, 5, 8, 4]
3. Pass 3:
- Find the minimum element in the remaining unsorted part (4). Swap it with the first element in the remaining unsorted part (8).
- Result: [1, 3, 4, 8, 5]
4. Pass 4:
- Find the minimum element in the remaining unsorted part (5). Swap it with the first element in the remaining unsorted part (8).
- Result: [1, 3, 4, 5, 8]
3
Matrix
1,1
M rows
3,4
29
Matrix Syntax
The declaration of a two-dimensional array (matrix) is done as follows:
Name: Array [1..rows , 1..clo] of type;
Or
Name: Array [rows , clo] of type;
Where:
Name: it’s the name of the matrix,
Rows and col: are the dimensions of the matrix,
Rows: the number of rows a matrix should have
Col: the number of columns a matrix should have
Type: the type of elements in the matrix
Example:
Mat: Array[ 3, 4] of Real; // Mat is a matrix of real numbers with 3 rows and 4 columns,
31
We want to display all the elements of the matrix: we need to use two loops, one to represent the rows
and the other to go through the columns
By rows: By columns:
For i ← 1 to 3 do For i ← 1 to 3 do
For j ← 1 to 4 do For j ← 1 to 4 do
write (Write (Mat [i][j])); write (Write (Mat [j][i]));
Done; Done;
Done; Done;
32
Exercise 3
Write an algorithm that finds the maximum value on a matrix with a dimension of N*N where N<=10,
Algorithm Max;
Const N ← 10;
var // Iterate through each element in the matrix
matrix: array[1..N, 1..N] of Integer; for i ← 1 to 3 do
S, maxelement,i,j :integer; for j ← 1 to 3 do
Begin // Update maxElement if a larger element is found
//Input the dimension of the matrix if (matrix[i][j] > maxElement) then
Write(“the dimension of the matrix is:”) maxElement ← matrix[i][j]; EIF;
Read (S); Done; Done;
// Input matrix elements from the user
for i ← 1 to S do // Output the result
for j ← 1 to S do print("The maximum element in the matrix is: ", maxElement);
write("Enter the element at position [", i, "][", j, "]: "); End.
Read(matrix[i][j]); Done;Done;
3
String
Classroom code :
Whz2ikh