You are on page 1of 30

More on Sorting:

Heapsort and Quicksort

Why sorting?
consider to be the most fundamental problem in
the study of algorithms
the need to sort information is inherent in an
application
Algorithms often use sorting as a key subroutine

Sorting classes
internal sorting algorithms

assume that data is stored in an array in main


memory

external sorting algorithm

assume that data is stored on disk or some other


device that is best accessed sequentially

Sorting Algorithms
Insertion sort
Selection sort
Bubble sort (in exam!)

Sorting Algorithms
Comparison Sort
Merge sort
Heapsort, and
Quicksort

Properties of Sorting Algorithms


In-place

The algorithm uses no additional array storage

Stable

if two elements that are equal remain in the same


relative position after sorting is completed

Quick View

Quick View

Sorting Algorithms

Mergesort
Quicksort
Heapsort

Quicksort
works recursively, by first selecting a random
pivot value from the array
Then it partitions the array into elements that are
less than and greater than the pivot
recursively sorts each part

Quicksort
This is considered an in-place sorting algorithm,
since it uses no other array storage
This algorithm is in the expected case, and in the
worst case.

Quicksort

Quicksort

Quicksort

Quicksort

Quicksort

Quicksort

Quicksort

Heapsort
based on a nice data structure, called a heap
supports the operations of inserting a key, and
deleting the element with the smallest key value
A heap can be built for n keys in time
the minimum key can be extracted in time
in-place sorting algorithm, but it is not stable

Heapsort
Heaps
Maintaining the heap property
Building a heap
The Heapsort algorithm

Heapsort
Heaps

Heapsort
Root is at A[i]

Heapsort
Order Property
min-heap
max-heap

Heapsort
Maintaining heap order:

Heapsort

Heapsort

Lower Bounds for ComparisonBased Sorting

Theorem:
Any comparison-based sorting algorithm has
worst-case running time

Linear Time Sorting


Counting Sort
Radix Sort
Bucket Sort

Linear Time Sorting: Counting Sort


Counting
sort assumes that each input is an

integer in the range from 1 to k


When , the sort runs in time.
The algorithm requires an additional
working storage but has the nice feature
that it is stable

Linear Time Sorting: Radix Sort


it is only practical for a very small ranges of
integers

You might also like