# Itec 3220

Document Sample

```					ITEC 2620M
Introduction to Data Structures

Instructor: Prof. Z. Yang
Course Website:
http://people.math.yorku.ca/~zyang/it
ec2620m.htm
Office: TEL 3049
Sorting
Key Points of this Lecture

• Recursive sorting algorithms
• Achieving leverage
• Quicksort
• Mergesort

3
Review

• Previous sorting algorithms were O(n2)
on average.
• What if we could get O(nlogn)
• Where have we seen O(logn) before?
– Binary search
– How did binary search work?
•first query explores 1 element
•second query explores 2 elements
•third query explores 4 elements

4
Recursive Sorting

• Split the elements into smaller sub-
groups
• Partially sort each sub-group
• Trust recursion to put everything back
together

5
Quicksort Algorithm
• Pick an element
– partially sort them
• move all larger elements on one side, and smaller elements on
the other
• have to look at all elements to get one element in position
• Pick one element in each sub-division (2)
– partially sort them
• move all elements as before (twice)
• have to look at half of the elements to get each new element
into position
• Pick one element in each sub-division (4)
– partially sort them
• move all elements as before (four times)
6
Quicksort Algorithm (Cont’d)
• Each sub-division is being sorted by the same
algorithm as the overall set
– recursion
– base case is 0 or 1 elements – already sorted
• Work to sort each element is cut in half each
level down
• Get twice as much done for our effort
• How many times can we cut something in half?
– O(logn)
• Pseudocode

7
Mergesort Algorithm
• Divide what you have to do into two halves
– sort each half
– merge the two halves into a fully sorted set
• Each half will be sorted by the same algorithm as
the overall set
– recursion
– base case is 0 or 1 elements – already sorted
• Each upward merge sorts twice as much
• How many times can we cut something in half?
– O(logn)
• Pseudocode
8

```
DOCUMENT INFO
Shared By:
Categories:
Tags:
Stats:
 views: 7 posted: 8/29/2012 language: English pages: 8