80 likes | 149 Views
COMP 171 Data Structures and Algorithms. Tutorial 3 Merge Sort & Quick Sort. Merge Sort. mergesort(A, left, right) if left < right then middle ← (left + right) / 2 mergesort(A, left, middle) mergesort(A, middle+1, right) merge(A, left, middle+1, right) end if
E N D
COMP 171Data Structures and Algorithms Tutorial 3 Merge Sort & Quick Sort
Merge Sort mergesort(A, left, right) if left < right then middle ← (left + right) / 2 mergesort(A, left, middle) mergesort(A, middle+1, right) merge(A, left, middle+1, right) end if end mergesort
merge(A, p, q, r) n1 ← q – p n2 ← r – q + 1 create array L[1..n1+1], R[1..n2+1] for i ← 1 to n1 do L[i] ← A[p+i-1] for j ← 1 to n2 do R[j] ← A[q+j-1] L[n1+1] ← R[n2+1] ← ∞ I ← j ← 1 for k ← p to r if L[I] < R[j] then A[k] ← L[i] i ← i + 1 else A[k] ← R[j] j ← j + 1 end if end for k end merge
Assume mergesort(A, left, right) takes T(n) to run where n = right – left + 1 = no. of elements in array A[left..right] • T(1) = O(1) • If array size = 1, nothing need to be done • T(n) = divide + conquer + combine = O(1) + 2T(n/2) + O(n) • T(1) = O(1) • T(n) = 2T(n/2) + O(n)
Best Case: Ω(n ㏒ n) • Worst Case: Ο(n ㏒ n) • Running Time: Θ(n ㏒ n) • Advantage • Stable running time • Fast running time • Disadvantage • Need extra memory space for merge step
Quick Sort quicksort(A, left, right) if left < right then middle ← partition(A, left, right) quicksort(A, left, middle–1 ) quicksort(A, middle+1, right) end if end quicksort
partition(A, left, right) x ← A[right] i ← left – 1 for j ← left to right – 1 if A[j] < x then i ← i + 1 swap(A[i], A[j]) end if end for j swap(A[i+1], A[right]) return i + 1 end partition
Advantage: • No extra memory is needed • Fast running time (in average) • Disadvantage: • Unstable in running time • Finding “pivot” element is a big issue!