Algorithms Intro
Algorithms Intro
Algorithms
Get ready to scuba dive into
the world of algorithms
Algorithms - Recap
Algorithms ?
Algorithm - Definition
2. Average Time
3. Worse Time
Definition: A straight line which a curve approaches arbitrarily closely, as they go to infinity. The limit
of the curve, its tangent "at infinity".
Big O Functions
f(n) Name Explanation
1 Constant f(n) = c
f(n) = logb(n) if & only if
x
log n Logarithmic b = n and b > 1
for us b = 2
n Linear f(n) = n
n log n Log Linear f(n) = n log n
2 2
n Quadratic f(n) = n
3 3
n Cubic f(n) = n
n n
2 Exponential f(n) = 2
n! Factorial f(n) = n!
Plot of Common Big O Functions
Constant Function
private static void simpleFunctionBasicOperations(int a,int b, int c) {
int sum = a + b;
int product = a * b * c;
int quotient = a * b / c;
System.out.println("\na + b = "+sum);
System.out.println("a * b * c = "+product);
System.out.println("a * b / c = "+quotient);
}
Also a Constant Function
int iteration = 1;
i = i * 2;
iteration ++;
}
Another Logarithmic Function
private static void halvingLoopVariable(int n) {
int iteration = 1;
i = i / 2;
iteration ++;
}
Linear Function
private static void simpleForLoop(int[] arr) {
System.out.println("For Loop");
for (int i =0 ; i< arr.length;i++) {
double sq = Math.pow(arr[i], 2);
System.out.println("Number : "+arr[i]+" Square : "+sq);
}
}
Another Linear Function
public static void twoForLoops(int[] arr) {
System.out.println("For Loop");
}
Cubic Functions
Another Cubic Function
Exponential Function
if (n == 0) return 1;
}
Factorial Function
PROBLEMS
• Write a program to check whether the given number is Odd or
Even.
• Write a program to print the natural number series till the given
number.
• Write a program to print the solid square pattern for the given
number.
• Write a java program to print the first N prime numbers with the
2
time complexity of O(N )
• It must change its state and move towards the base case
also called as the recursive step.
• Indirect Recursion : When a function calls another function which calls the
first function
• Tail Recursion : If the function is calling itself and the recursive call is the last
statement executed by the function
• Non Tail/Head Recursion : If the function is calling itself and the recursive
call is the first statement of of the function
• f(0) = f(1) = 1
if(n==0) {
return 0;
if (n ==1 || n == 2) {
return 1;
}
Staircase Problem
• How many ways there are to reach the top of the staircase. i.e: find
number of ways to climb top of staircase.
Staircase Problem – Recursive
Solution
Robot Maneuvering
• The robot can only move either down or right at any point in time. The
robot is trying to reach the bottom-right corner of the grid.
• Linear Search
• Binary Search
Linear Search
020 604 205 024 200 195 493 520 720 402
Is this 205?
Linear Search Algorithm
Binary Search
• If the input list is already sorted, then linear search is not an
efficient way of searching.
• In this case it is possible to perform the search much faster, because
the order of the elements in the list guides the search.
• Since it is already sorted, we can select a central point and check if
the value at the central point is the same or higher or lower than the
item to be searched.
• If it is same, the search ends there, if it is high then we search for
elements from 1 – the mid point and if it is low then we search for
elements from mid point to end of array.
Binary Search Algorithm
020 024 195 200 205 402 493 520 604 720
Is this 520?
Binary Search Algorithm
020 024 195 200 205 402 493 520 604 720
Is this 520?
Binary Search Algorithm
Binary Search Algorithm
Recursive
Binary Search – Time Complexity
• Selection Sort
• Insertion Sort
• Merge Sort
• Quick Sort
• Heap Sort
Bubble Sort
• If the elements are in the wrong order they are swapped, if not,
move on to the next pair.
Bubble Sort
Bubble Sort - Complexity
• Improves on the bubble sort by making only one exchange for every
pass through the list.
• A selection sort looks for the largest value as it makes a pass and, after
completing the pass, places it in the proper location.
2
• Still has the complexity of O(N )
Selection Sort - Working
Insertion Sort
2
• The insertion sort, although still O(N ), works in a slightly different
way.
• Each new item is then “inserted” back into the previous sublist such
that the sorted sublist is one item larger.
Insertion Sort - Working
Merge Sort
• Uses divide and conquer strategy
• If the list is empty or has one item, it is sorted by definition (the base case)
• If the list has more than one item, we split the list and recursively invoke a merge
sort on both halves
• Once the two halves are sorted, the fundamental operation, called a merge, is
performed.
• Merging is the process of taking two smaller sorted lists and combining them
together into a single, sorted, new list
• Complexity is O(nlogn)
Merge Sort - Working
Quick Sort
• Uses the same divide and conquer of merge sort with less
additional space.
• Selects a value called pivot value, which is mostly the first time
(for simplicity sake). This value is used for arriving at the
splitting the list.
• The actual value where the pivot value actually arrives at the
sorted list is the split point.
• Complexity is O (N log N)
Quick Sort - Working
Heap Sort
• The max element should be at the root, remove that and add it
to the final sorted list and then replace the root with the last item
in the heap.
• Repeat the above two steps until all elements are sorted.
Heap Sort - Working
Greedy Algorithms
What is Greedy Algorithm
• A greedy algorithm constructs a solution to the problem by
always making a choice that looks the best at the moment.
• B–9
• C – 12
• D – 13
• E – 16
• F - 45
Algorithm - Huffman
Knapsack Problem
• Suppose a hitch-hiker has to fill up his knapsack by selecting
from among various possible objects those which will give him
maximum comfort