Algorithm Types
Algorithm Types
CS2002
Algorithms
Algorithm Types
• Algorithm types we will consider include:
– Simple recursive algorithms
– Backtracking algorithms
– Divide and conquer algorithms
– Dynamic programming algorithms
– Greedy algorithms
– Branch and bound algorithms
– Brute force algorithms
– Randomized algorithms
Divide and Conquer
• A divide and conquer algorithm consists of
two parts:
– Divide the problem into smaller subproblems
of the same type, and solve these subproblems
recursively
– Combine the solutions to the subproblems into
a solution to the original problem
• Traditionally, an algorithm is only called
divide and conquer if it contains two or
more recursive calls
Divide & Conquer Example: Quick Sort
(ref 7.3 Data Structures in C++)
The quick sort scheme developed by C. A. R.
Hoare has the best average behavior among all
the sorting methods we shall be studying
Given (R0, R1, …, Rn-1) and Ki denote a pivot key
If Ki is placed in position s(i),
then Kj Ks(i) for j < s(i), Kj Ks(i) for j > s(i).
After a positioning has been made, the original
file is partitioned into two subfiles, {R0, …, Rs(i)-1},
Rs(i), {Rs(i)+1, …, Rs(n-1)}, and they will be sorted
independently
Quick Sort
• Quick Sort Concept
– select a pivot key
– interchange the elements to their correct
positions according to the pivot
– the original file is partitioned into two subfiles
and they will be sorted independently
Quick Sort Program
Left =0, right=9
}
Iterative Merge Sort
1. We assume that the input sequence has n
sorted lists, each of length 1.
2. We merge these lists pairwise to obtain n/2
lists of size 2.
3. We then merge the n/2 lists pairwise, and so
on, until a single list remains.
4. It works bottom-up
void MergeSort(Element *list, const int
n)
{
Element *tempList = new Element[n];
for (int l =1; l<n; l*=2)
{
MergePass(list, tempList, n, l );
l = l *2;
MergePass(tempList, list, n, l ) void MergePass(Element *initlist, Element *resultlist,
const int n,
}
const int l)
delete tempList;
{
}
for (int i =1; i<=n-2*l+1; i=i+2*l)
{
merge(initList, resultList, i, i+l-1;i+2*l-1);
}
resultList
initList
resultList
initList
• Analysis
– Total number of passes is the ceiling of log 2n
– merge two sorted list in linear time: O(n)
– The total computing time is O(n log n) in all
cases.
– Stable ( depending on underlying merge)
– Not-in-place
Recursive Merge Sort (arrays)
(works top down)
similar to the one given in Program 7.11 for linked lists
}
Homework
• Show how the basic mergesort that we saw
in class would work on the following array
of numbers
15 8 7 2 3 6 9 10 1 11 12 0 4 5 13 14
Merge (linked lists)
similar to the one given in Program 7.12
Node ListMerge(Node a, Node b) // first nodes of the 2 sorted linked blists
{
Node dummy= new Node();
Node head = dummy, c = head;
Node ListMergesort(Node c)
{
if ( c== null || c.next == null) return c;