Professional Documents
Culture Documents
In this technique, the two successive items a [ j ] and a[ j+1] are exchanged
whenever a [ j ]>= a[ j+1]
Pass 1
Eg : 40 50 30 20 10
a [0] 40 40 40 40 40 30
a [1] 50 50 30 30 30 40
a [2] 30 30 50 20 20 20
a[3] 20 20 20 50 10 10
a 4] 10 10 10 10 50 50
30 30 20 20 10
20 20 30 10 20
40 10 10 30 30
10 40 40 40 40
50 50 50 50 50
it is not easy to tell because it If the input is already sorted then no swap will occur.
swaps when two consecutive If the input is sorted in some places then swap will
elements are not in the order occur only in those places.
It is theta n2 because it does not depend on best case , worst case or average case
Bubble sort - Exercise
• .
Pros and cons
• This algorithm is not very popular, however it is still useful.
• The bubble sort compares adjacent items and swaps them if they are out of
order.
• During each pass, until the array is sorted, the algorithm traverses through
the data and compares adjacent items, swapping them if they are not in
ascending order.
• It is simple to understand and implement.
• However, this sort requires several passes over the data, and thus
introduces a major factor of inefficiency.
Bubble sort :Improved version
j=0, j<n-i-1
L4
Bubble sort
if bubble sort makes no exchanges on its pass through a list, the list
is sorted and the algorithm can be stopped.
A list is sorted if and only if all its adjacent elements are in a correct
order.
Bubble sort
Write pseudocode of the method that incorporates this improvement.
int min = i;
for (int j = i + 1; j < n; j++)
if (a[min] > a[j])
min = j;
// Move minimum element at current i.
int key = a[min];
while (min > i)
{
a[min] = a[min - 1];
min--;
}
a[i] = key;
}
}
Polynomial
Θ(n2)
Polynomial P(x) = 2x2 +4x +5
p[2] p[1] p[0]
P I (2 power J (1 to i)
to 0)
0 2 1
1*x 1
X*x 2
0+p[2]*x2 3
2x2
1 1
1*x 1
2x2 + 4x 2
0 1 -----
Polynomial
Analyzing what unnecessary computations the quadratic algorithm does should lead you
to a better (linear) algorithm.
Polynomial
The above algorithm is very inefficient: we recompute powers of x again and again
as if there were no relationship among them.
If we proceed from the highest term to the lowest, we could compute xi−1 by using xi
but this would require a division and hence a special treatment for x = 0.
Alternatively, we can move from the lowest term to the highest and compute xi by
using xi−1.
Since the second alternative uses multiplications instead of divisions and does not
require any special treatment for x = 0, it is both more efficient and cleaner.
10+5x+4x2+7x3+8x4
Simple method
O(n)
Polynomial
Is it possible to design an algorithm with a better than linear efficiency for this
problem?
How many coefficients does a polynomial of degree n have? Can one compute its value
at an arbitrary point without processing all of them?
Ans: Note that the number of desired substrings that starts with an A at a
given position i (0 ≤ i < n − 1) in the text is equal to the number of B’s
to the right of that position. This leads to the following simple algorithm:
Example 1: Traveling Salesman
Problem
• Given n cities with known distances between
each pair, find the shortest tour that passes
through all the cities exactly once before
returning to the starting city
• Alternatively: Find shortest Hamiltonian circuit
2
in a weighted connected graph a b
5 3
• Example: 8 4
c d
How do we represent a solution (Hamiltonian circuit)? 7
a
2
b TSP by Exhaustive Search
5 3
8 4
c d
7
Tour Cost
a→b→c→d→a 2+3+7+5 = 17
a→b→d→c→a 2+4+7+8 = 21
a→c→b→d→a 8+3+4+5 = 20
a→c→d→b→a 8+7+4+2 = 21
a→d→b→c→a 5+4+3+8 = 20
a→d→c→b→a 5+7+3+2 = 17
Travelling Salesman Problem(TSP)
In other words, given two integer arrays val[0..n-1] and wt[0..n-1] which represent
values and weights associated with n items respectively.
Also given an integer W which represents knapsack capacity, find out the maximum
value subset of val[] such that sum of the weights of this subset is smaller than or
equal to W.
You cannot break an item, either pick the complete item, or don’t pick it (0-1
property).
• An item is either chosen or not chosen. A bit string of 0’s and 1’s
is generated which is of length n. If the ith symbol of a bit string
is 0, then the ith item is not chosen and if it is 1, the ith item is
chosen.
Knapsack problem
• ALGORITHM BruteForce (Weights [1 … N], Values [1 … N], A[1…N])
• //Finds the best possible combination of items for the KP
• //Input: Array Weights contains the weights of all items
• Array Values contains the values of all items
• Array A initialized with 0s is used to generate the bit strings
• //Output: Best possible combination of items in the knapsack bestChoice [1 .. N]
Try it out
A thief is robbing a store and can carry a maximal weight of W into his knapsack. There
are n items and weight of ith item is wi and the profit of selecting this item is pi. What
items should the thief take?
Assignment Problem- Hungarian method
• Assignment
– Something : job, task
– Someone : machine , people
The Hungarian algorithm, utilizes the theorem for polynomial runtime complexity
(worst case O(n3)) and guaranteed optimality:
If a number is added to or subtracted from all of the entries of any one row or
column of a cost matrix, then an optimal assignment for the resulting cost matrix is
also an optimal assignment for the original cost matrix.
Assignment Problem- Hungarian method
Perform row subtraction
Reduced matrix
Assignment Problem- Hungarian method
• Draw minimum number of lines(vertical / horizontal) which cover all the
lines
where would you send each of your salespeople in order to minimize fair?
Assignment Problem- Hungarian method - II
Row subtraction
Column subtraction
No.of lines=3
N= 4
No.of lines != N
Reduced matrix
Assignment Problem- Hungarian method - II
Allocation
Assignment Problem- Hungarian method – unbalanced matrix
Convert the matrix into n*n matrix
• A- Nishant , Abhishek
• D- Anurag
L13
Decrease and conquer
Decrease and conquer involves reducing the problem, while Divide and conquer
reduces the problem into several sub problems
Application
• Insertion Sort
Improvement
• Use binary search to reduce the number of comparisons in
normal insertion sort.
• Binary Insertion Sort uses binary search to find the proper
location to insert the selected item at each iteration.
• In normal insertion, sorting takes O(i) (at ith iteration) in
worst case.
• We can reduce it to O(log i) by using binary search.
• The algorithm, as a whole, still has a running worst case
running time of O(n2) because of the series of swaps required
for each insertion.
• How to implement Insertion Sort for Linked List?
Try it out later !!!
• Do an insertion sort on the following example: "CHRIST". Write down the
essence of insertion sort and also a proper pseudocode.
Topological sorting