session 10,11 (algorithm)
session 10,11 (algorithm)
Eng.Alaa Osama
1.
Session 10,11
Algorithms
collection of values as input and produces the output(s) needed to solve a problem.
• Algorithms are used to solve problems or automate tasks in a systematic and efficient manner.
They are a set of instructions or rules that guide the computer or software in performing a
particular task or solving a problem.
▪ Program:-
✓ Must be performed by a machine
1- int x; X
2- int y=20; 1
4- {} X
8- cout<<x 1
Examples:
total=0; 1
for (int i=1 ; i<=n ; i++) n-1+1+1=n+1
{
total=total+i; // less than the SE of for loop by 1 n
}
return total; 1
}
SE = 1+n+1+n+1 = 2n+3 => O(n)
3. int func (int a[],int n) x
{
int x=5; 1
for (int i=1; i<=n ; i++) n+1
{
for (int j=1; j<=n ; j++) n
{
n-1 *n
x=x+i+j;
cout<<x;
} n-1
}
}
sequential search is made over all items one by one. Every item is checked and
if a match is found then that item is returned, otherwise the search continues till
the end of the data collection.
Code:
▪ Binary search: is a fast search algorithm with run-time complexity of Ο(log n).
This search algorithm works on the principle of divide and conquer. For this
algorithm to work properly, the data collection should be in the sorted form.
Example: search element is 87
Code:
Selection sort :
▪ Algorithm
- Find the minimum element from the array of size N and swap it with the
element at front
- Find the minimum element from the array of size N-1 and swap it with
element at front
- you aredone!
Example:
▪ Code:
Insertion sort :
▪ Algorithm
- Start from left and put the element in the correct order.
Example:
Let’s apply the steps to the following list of numbers 4 -1 6 5 8 3 7 2 1 0:
▪ Code:
Bubble sort :
▪ Algorithm
Example:
▪ Code:
Merge sort :
- then merging the sorted subarrays back together to form the final sorted
array.
▪ Example:
▪ Code: