1 / 8

COMP 171 Data Structures and Algorithms

Learn about merge sort and quick sort algorithms, their advantages, disadvantages, and running time complexities. Understand how to implement and analyze these popular sorting algorithms.

fbrink
Télécharger la présentation

COMP 171 Data Structures and Algorithms

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. COMP 171Data Structures and Algorithms Tutorial 3 Merge Sort & Quick Sort

  2. 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

  3. 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

  4. 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)

  5. 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

  6. 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

  7. 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

  8. Advantage: • No extra memory is needed • Fast running time (in average) • Disadvantage: • Unstable in running time • Finding “pivot” element is a big issue!

More Related