COMP 171 Data Structures and Algorithms - PowerPoint PPT Presentation

About This Presentation
Title:

COMP 171 Data Structures and Algorithms

Description:

COMP 171 Data Structures and Algorithms Tutorial 3 Merge Sort & Quick Sort Merge Sort mergesort(A, left, right) if left – PowerPoint PPT presentation

Number of Views:71
Avg rating:3.0/5.0
Slides: 9
Provided by: Vincen204
Category:

less

Transcript and Presenter's Notes

Title: COMP 171 Data Structures and Algorithms


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

2
Merge Sort
  • mergesort(A, left, right)
  • if left lt right then
  • middle ? ?(left right) / 2?
  • mergesort(A, left, middle)
  • mergesort(A, middle1, right)
  • merge(A, left, middle1, right)
  • end if
  • end mergesort

3
  • merge(A, p, q, r)
  • n1 ? q p
  • n2 ? r q 1
  • create array L1..n11, R1..n21
  • for i ? 1 to n1 do Li ? Api-1
  • for j ? 1 to n2 do Rj ? Aqj-1
  • Ln11 ? Rn21 ? 8
  • I ? j ? 1
  • for k ? p to r
  • if LI lt Rj then
  • Ak ? Li
  • i ? i 1
  • else
  • Ak ? Rj
  • 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 Aleft..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 O(n ? n)
  • Worst Case ?(n ? n)
  • Running Time T(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 lt right then
  • middle ? partition(A, left, right)
  • quicksort(A, left, middle1 )
  • quicksort(A, middle1, right)
  • end if
  • end quicksort

7
  • partition(A, left, right)
  • x ? Aright
  • i ? left 1
  • for j ? left to right 1
  • if Aj lt x then
  • i ? i 1
  • swap(Ai, Aj)
  • end if
  • end for j
  • swap(Ai1, Aright)
  • 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!
Write a Comment
User Comments (0)
About PowerShow.com