ADA Algorithms
ADA Algorithms
3. Merge Sort:
ALGORITHM Mergesort(A[0..n−1])
//Sorts array A[0..n − 1]by recursive mergesort
//Input: An array A[0..n − 1]of orderable elements
//Output: Array A[0..n − 1]sorted in nondecreasing order
if n>1
copy A[0.. n/2 −1]to B[0.. n/2 −1]
copy A[ n/2 ..n−1]to C[0.. n/2 −1]
Mergesort(B[0.. n/2 −1])
Mergesort(C[0.. n/2 −1])
Merge(B, C, A) //see below
4. Quick Sort:
ALGORITHM Quicksort(A[l..r])
//Sorts a subarray by quicksort
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r
//Output: Subarray A[l..r] sorted in nondecreasing order
if l < r
s ← Partition(A[l..r]) // s is a split position
Quicksort(A[l..s − 1])
Quicksort(A[s + 1..r])
ALGORITHM HoarePartition(A[l..r])
//Partitions a subarray by Hoare’s algorithm, using the first element as a pivot
//Input: Subarray of array A[0..n − 1], defined by its left and right indices l and r (l < r)
//Output: Partition of A[l..r], with the split position returned as this function’s value
p ← A[l]
i ← l; j ← r + 1
repeat
repeat i ← i + 1 until A[i] ≥ p
repeat j ← j - 1 until A[j] ≤ p
swap(A[i], A[j])
until i ≥ j
swap(A[i], A[j]) //undo last swap when i ≥ j
swap(A[l], A[j])
return j
5. Heap Sort:
ALGORITHM heapBottomUp(H[1..n])
// Constructs a heap from elements of a given array by the bottom-up algorithm
// Input: An array H[1..n] of orderable items
// Output: A heap H[1..n]
if j < n then
if H[j] < H[j + 1] then
j←j+1
if v ≥ H[j] then
heapMade ← 1
else
H[k] ← H[j]
k←j
H[k] ← v
ALGORITHM heapSort(H[1..n])
// Sorts an array using heap sort
// Input: An array H[1..n] of orderable items
// Output: Array H[1..n] sorted in non-decreasing order
heapBottomUp(H, n)
for i ← n downto 2 do
swap(H[1], H[i])
n←n-1
heapBottomUp(H, n)
ALGORITHM Floyd(W[1..n,1..n])
// Implements Floyd’s algorithm for the all-pairs shortest-paths problem
// Input: The weight matrix W of a graph with no negative-length cycle
// Output: The distance matrix of the shortest paths’ lengths
ALGORITHM Prim(G)
// Prim’s algorithm for constructing a minimum spanning tree
// Input: A weighted connected graph G = (V, E)
// Output: ET, the set of edges composing a minimum spanning tree of G
VT ← {v0} // Initialize the set of tree vertices with any vertex (here v0)
ET ← ∅ // Initialize the set of edges in the minimum spanning tree as empty
for i ← 1 to |V| - 1 do
Find a minimum-weight edge e* = (v*, u*) among all edges (v, u) such that v is in VT and u is in V - VT
VT ← VT ∪ {u*}
ET ← ET ∪ {e*}
return ET
9. Fractional Knapsack:
ALGORITHM FractionalKnapsack(W, v, n, C)
// Solves the Fractional Knapsack problem using greedy method
// Input: Array W of item weights, array v of item values, number of items n, and knapsack capacity C
// Output: Maximum value that can be obtained
Print shortest path distances and paths from src to each vertex