308-203A Introduction to Computing II Lecture 8: Sorting 2 - PowerPoint PPT Presentation

About This Presentation
Title:

308-203A Introduction to Computing II Lecture 8: Sorting 2

Description:

2. MergeSort - Divide-and-Conquer. O(n log n) worst-case optimal. The ... Divide-and-Conquer was good, can we do. the same thing with an operation other than ... – PowerPoint PPT presentation

Number of Views:24
Avg rating:3.0/5.0
Slides: 12
Provided by: alfre6
Category:

less

Transcript and Presenter's Notes

Title: 308-203A Introduction to Computing II Lecture 8: Sorting 2


1
308-203AIntroduction to Computing IILecture 8
Sorting 2
Fall Session 2000
2
So far.
1. Bubblesort - intuitive implementation O(n2)
suboptimal 2. MergeSort - Divide-and-Conquer O
(n log n) worst-case optimal
3
The Problem with MergeSort
We do a lot of copying when we MERGE
N/2
N/2
8, 34, 51, 78, 82
2, 17, 64, 91, 123
2, 8, 17, 34, 51, 64, 78, 82, 91, 123
New Array size N
4
In Java, for example...
int merge(int a, int b) int c
new int a.length b.length // merge a
and b into c . return c
5
The Problem with MergeSort
  • To merge we need O(n) extra space
  • Copying bigger hidden constants
  • Sorting-in-place would be preferable
  • (if we can do it in optimal n log n)
  • Divide-and-Conquer was good, can we do
  • the same thing with an operation other than
  • merge??

6
Quicksort
1. Pick pivot
64, 8, 78, 34, 82, 51, 17, 2, 91, 123
2. Partition
8, 34, 51, 17, 2 , 64, 78, 82, 91, 123
2. Recursion
2, 8, 17, 34, 51, 64, 78, 82, 91, 123
7
Quicksort
Quicksort(int A, int start, int end) int
pivot A0 int midpoint
Partition(pivot, A) Quicksort(A, start,
midpoint) Quicksort(A, midpoint1, end)
8
Running Time
  • Depends significantly on choice of pivot
  • Worst-case O(n2)
  • Best-case O( n log n)

Proofs on separate handout
9
The Worst-Case is WORSE!
  • Worst-case is O(n2) as bad as Bubblesort
  • A clever trickFooling-the-Adversary
  • 1. pick a random pivot
  • 2. You hit a bad case only when very unlucky
  • Average-case O( n log n)

Proof beyond the scope of this course
10
Randomized Quicksort
Quicksort(int A, int start, int end) int
pivot A randomInt(start, end) int
midpoint partition(pivot, A) Quicksort(A,
start, midpoint) Quicksort(A, midpoint1,
end)
11
Any questions?
Write a Comment
User Comments (0)
About PowerShow.com