lecture-12

lecture-12 - CPSC 223 Algorithms Data Abstract Structures...

Info iconThis preview shows pages 1–5. Sign up to view the full content.

View Full Document Right Arrow Icon
10/12/10 1 CPSC 223 Algorithms & Data Abstract Structures Lecture 12: More on Sorting – Mergesort and Quicksort Today … Continuing with Sorting Mergesort [Sect. 9.2, pp. 466-472] Quicksort [Sect. 9.2, pp. 472-484] CPSC 223 -- Fall 2010 2
Background image of page 1

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
10/12/10 2 Mergesort CPSC 223 -- Fall 2010 3 Mergesort [von Neumann, 1945] A “divide and conquer” approach The basic idea: Divide the list into two halves Sort each half Merge the sorted halves … Merging is fast when the two sublists are sorted CPSC 223 -- Fall 2010 4 29 10 14 13 29 10 14 13 Ini±al list: ( n =4) 29 10 14 13 Split Sort Merge 10 29 13 14 10 29 13 14 10 13 14 29
Background image of page 2
10/12/10 3 Mergesort Given that mergesort merges two sorted lists to create a (larger) sorted list How do we sort the two sublists? Using mergesort! Divide the list into two halves, sort each half (using mergesort), and then merge the sorted halves Mergesort is deFned using recursion CPSC 223 -- Fall 2010 5 Mergesort CPSC 223 -- Fall 2010 6 29 10 14 13 Ini±al list ( n =4) 29 10 14 13 Split 29 10 14 13 Split ( 1-element lists are sorted by defni2on ) Merge 10 29 13 14 10 13 14 29 Merge
Background image of page 3

Info iconThis preview has intentionally blurred sections. Sign up to view the full version.

View Full Document Right Arrow Icon
10/12/10 4 Mergesort (based on textbook) void Mergesort (Entry theArray[], int n, int frst, int last) { iF(frst < last) { int mid = (frst + last) / 2; Mergesort (theArray, n, frst, mid); Mergesort (theArray, n, mid + 1, last); Merge (theArray, n, frst, mid, last); } } CPSC 223 -- Fall 2010 7 Mergesort (based on textbook) void Merge (Entry theArray[], int n, int frst, int mid, int last) { Entry tmpArray[n]; int frst1 = frst, frst2 = mid + 1, i = frst1; For(; frst1 <= mid && frst2 <= last; i++) { iF(theArray[frst1] < theArray[frst2])
Background image of page 4
Image of page 5
This is the end of the preview. Sign up to access the rest of the document.

{[ snackBarMessage ]}

Page1 / 11

lecture-12 - CPSC 223 Algorithms Data Abstract Structures...

This preview shows document pages 1 - 5. Sign up to view the full document.

View Full Document Right Arrow Icon
Ask a homework question - tutors are online