SlideShare uma empresa Scribd logo
1 de 26
Lower Bound for sorting
Linear-Time Sorting Algorithms
Sorting So Far
Insertion sort:
Easy to code
Fast on small inputs (less than ~50 elements)
Fast on nearly-sorted inputs
O(n2
) worst case
O(n2
) average (equally-likely inputs) case
O(n2
) reverse-sorted case
Sorting So Far
Merge sort:
Divide-and-conquer:
Split array in half
Recursively sort sub arrays
Linear-time merge step
O(n lg n) worst case
Doesn’t sort in place
Sorting So Far
Heap sort:
Uses the very useful heap data structure
Complete binary tree
Heap property: parent key > children’s keys
O(n lg n) worst case
Sorts in place
Fair amount of shuffling memory around
Sorting So Far
Quick sort:
Divide-and-conquer:
Partition array into two sub-arrays, recursively sort
All of first sub-array < all of second sub-array
No merge step needed!
O(n lg n) average case
Fast in practice
O(n2
) worst case
Naïve implementation: worst case on sorted input
Address this with randomized quicksort
How Fast Can We Sort?
We will provide a lower bound, then beat it
How do you suppose we’ll beat it?
First, an observation: all of the sorting
algorithms so far are comparison sorts
The only operation used to gain ordering
information about a sequence is the pair-wise
comparison of two elements
Theorem: all comparison sorts are Ω(n lg n)
Decision Trees
Decision trees provide an abstraction of
comparison sorts
A decision tree represents the comparisons made
by a comparison sort. Every thing else ignored
What do the leaves represent?
How many leaves must there be?
Decision Trees
Decision trees can model comparison sorts.
For a given algorithm:
One tree for each n
Tree paths are all possible execution traces
What’s the longest path in a decision tree for
insertion sort? For merge sort?
What is the asymptotic height of any decision
tree for sorting n elements?
Answer: Ω(n lg n) (now let’s prove it…)
Lower Bound For
Comparison Sorting
Thm: Any decision tree that sorts n elements
has height Ω(n lg n)
What’s the minimum no. of leaves?
What’s the maximum no. of leaves of a binary
tree of height h?
Clearly the minimum no of leaves is less than
or equal to the maximum no. of leaves
Lower Bound For
Comparison Sorting
So we have…
n! ≤ 2h
Taking logarithms:
lg (n!) ≤ h
Stirling’s approximation tells us:
Thus:
n
e
n
n 





>!
n
e
n
h 





≥ lg
Lower Bound For
Comparison Sorting
So we have
Thus the minimum height of a decision tree is
Ω(n lg n)
( )nn
ennn
e
n
h
n
lg
lglg
lg
Ω=
−=






≥
Lower Bound For
Comparison Sorts
Thus the time to comparison sort n elements is
Ω(n lg n)
Corollary: Heapsort and Mergesort are
asymptotically optimal comparison sorts
But the name of this lecture is “Sorting in
linear time”!
How can we do better than Ω(n lg n)?
Sorting In Linear Time
Counting sort
No comparisons between elements!
But…depends on assumption about the numbers
being sorted
We assume numbers are in the range 1.. k
The algorithm:
Input: A[1..n], where A[j] ∈ {1, 2, 3, …, k}
Output: B[1..n], sorted (notice: not sorting in place)
Also: Array C[1..k] for auxiliary storage
Counting Sort
1 CountingSort(A, B, k)
2 for i=1 to k
3 C[i]= 0;
4 for j=1 to n
5 C[A[j]] += 1;
6 for i=2 to k
7 C[i] = C[i] + C[i-1];
8 for j=n downto 1
9 B[C[A[j]]] = A[j];
10 C[A[j]] -= 1;
Work through example: A={4 1 3 4 3}, k = 4
Counting Sort
1 CountingSort(A, B, k)
2 for i=1 to k
3 C[i]= 0;
4 for j=1 to n
5 C[A[j]] += 1;
6 for i=2 to k
7 C[i] = C[i] + C[i-1];
8 for j=n downto 1
9 B[C[A[j]]] = A[j];
10 C[A[j]] -= 1;
What will be the running time?
Takes time O(k)
Takes time O(n)
Counting Sort
Total time: O(n + k)
Usually, k = O(n)
Thus counting sort runs in O(n) time
But sorting is Ω(n lg n)!
No contradiction--this is not a comparison sort (in
fact, there are no comparisons at all!)
Notice that this algorithm is stable
Counting Sort
Cool! Why don’t we always use counting
sort?
Because it depends on range k of elements
Could we use counting sort to sort 32 bit
integers? Why or why not?
Answer: no, k too large (232
= 4,294,967,296)
David Luebke 20 08/01/13
Radix Sort
Intuitively, you might sort on the most
significant digit, then the second msd, etc.
Problem: lots of intermediate piles of cards
(read: scratch arrays) to keep track of
Key idea: sort the least significant digit first
RadixSort(A, d)
for i=1 to d
StableSort(A) on digit i
Radix Sort
Can we prove it will work?
Sketch of an inductive argument (induction on
the number of passes):
Assume lower-order digits {j: j<i}are sorted
Show that sorting next digit i leaves array correctly
sorted
If two digits at position i are different, ordering numbers
by that digit is correct (lower-order digits irrelevant)
If they are the same, numbers are already sorted on the
lower-order digits. Since we use a stable sort, the
numbers stay in the right order
Radix Sort
What sort will we use to sort on digits?
Counting sort is obvious choice:
Sort n numbers on digits that range from 1..k
Time: O(n + k)
Each pass over n numbers with d digits takes
time O(n+k), so total time O(dn+dk)
When d is constant and k=O(n), takes O(n) time
How many bits in a computer word?
Radix Sort
Problem: sort 1 million 64-bit numbers
Treat as four-digit radix 216
numbers
Can sort in just four passes with radix sort!
Compares well with typical O(n lg n)
comparison sort
Requires approx lg n = 20 operations per number
being sorted
So why would we ever use anything but radix
sort?
Radix Sort
In general, radix sort based on counting sort is
Fast
Asymptotically fast (i.e., O(n))
Simple to code
A good choice
To think about: Can radix sort be used on
floating-point numbers?
The End

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Sorting
SortingSorting
Sorting
 
Sorting
SortingSorting
Sorting
 
Radix and shell sort
Radix and shell sortRadix and shell sort
Radix and shell sort
 
Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)Counting sort(Non Comparison Sort)
Counting sort(Non Comparison Sort)
 
Array linear data_structure_2 (1)
Array linear data_structure_2 (1)Array linear data_structure_2 (1)
Array linear data_structure_2 (1)
 
Presentation
PresentationPresentation
Presentation
 
Lect11 Sorting
Lect11 SortingLect11 Sorting
Lect11 Sorting
 
Sorting
SortingSorting
Sorting
 
Heaps & Adaptable priority Queues
Heaps & Adaptable priority QueuesHeaps & Adaptable priority Queues
Heaps & Adaptable priority Queues
 
Algorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching AlgorithmsAlgorithms Lecture 6: Searching Algorithms
Algorithms Lecture 6: Searching Algorithms
 
Maps&hash tables
Maps&hash tablesMaps&hash tables
Maps&hash tables
 
Best,worst,average case .17581556 045
Best,worst,average case .17581556 045Best,worst,average case .17581556 045
Best,worst,average case .17581556 045
 
Sorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha MajumderSorting Seminar Presentation by Ashin Guha Majumder
Sorting Seminar Presentation by Ashin Guha Majumder
 
Sortsearch
SortsearchSortsearch
Sortsearch
 
Radix sorting
Radix sortingRadix sorting
Radix sorting
 
Insertion sort
Insertion sortInsertion sort
Insertion sort
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
Sorting Algorithms
Sorting AlgorithmsSorting Algorithms
Sorting Algorithms
 
Divide and conquer 1
Divide and conquer 1Divide and conquer 1
Divide and conquer 1
 
Sorting ppt
Sorting pptSorting ppt
Sorting ppt
 

Destaque

Recommendations for the Shear Assessment of Reinforced Concrete Solid Slab Br...
Recommendations for the Shear Assessment of Reinforced Concrete Solid Slab Br...Recommendations for the Shear Assessment of Reinforced Concrete Solid Slab Br...
Recommendations for the Shear Assessment of Reinforced Concrete Solid Slab Br...Eva Lantsoght
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower boundsRajendran
 
5 cramer-rao lower bound
5 cramer-rao lower bound5 cramer-rao lower bound
5 cramer-rao lower boundSolo Hermelin
 
Counting Sort and Radix Sort Algorithms
Counting Sort and Radix Sort AlgorithmsCounting Sort and Radix Sort Algorithms
Counting Sort and Radix Sort AlgorithmsSarvesh Rawat
 
Chapter 10 software certification
Chapter 10 software certificationChapter 10 software certification
Chapter 10 software certificationdespicable me
 
Chapter 5 software design
Chapter 5 software designChapter 5 software design
Chapter 5 software designdespicable me
 
Boundary and equivalnce systematic test design
Boundary and equivalnce   systematic test designBoundary and equivalnce   systematic test design
Boundary and equivalnce systematic test designIan McDonald
 
software testing
 software testing software testing
software testingSara shall
 
Equivalence partitioning
Equivalence partitioningEquivalence partitioning
Equivalence partitioningSarjana Muda
 
Equivalence partinioning and boundary value analysis
Equivalence partinioning and boundary value analysisEquivalence partinioning and boundary value analysis
Equivalence partinioning and boundary value analysisniharika5412
 
Software Testing Life Cycle
Software Testing Life CycleSoftware Testing Life Cycle
Software Testing Life Cyclegueste730d5
 
Seminar on Software Testing
Seminar on Software TestingSeminar on Software Testing
Seminar on Software TestingBeat Fluri
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSGayathri Gaayu
 
Chapter 2 software development life cycle models
Chapter 2 software development life cycle modelsChapter 2 software development life cycle models
Chapter 2 software development life cycle modelsdespicable me
 

Destaque (20)

Lower bound
Lower boundLower bound
Lower bound
 
Recommendations for the Shear Assessment of Reinforced Concrete Solid Slab Br...
Recommendations for the Shear Assessment of Reinforced Concrete Solid Slab Br...Recommendations for the Shear Assessment of Reinforced Concrete Solid Slab Br...
Recommendations for the Shear Assessment of Reinforced Concrete Solid Slab Br...
 
Chap 14
Chap 14Chap 14
Chap 14
 
Divide and conquer surfing lower bounds
Divide and conquer  surfing lower boundsDivide and conquer  surfing lower bounds
Divide and conquer surfing lower bounds
 
5 cramer-rao lower bound
5 cramer-rao lower bound5 cramer-rao lower bound
5 cramer-rao lower bound
 
Counting Sort and Radix Sort Algorithms
Counting Sort and Radix Sort AlgorithmsCounting Sort and Radix Sort Algorithms
Counting Sort and Radix Sort Algorithms
 
Chapter 10 software certification
Chapter 10 software certificationChapter 10 software certification
Chapter 10 software certification
 
Chapter 5 software design
Chapter 5 software designChapter 5 software design
Chapter 5 software design
 
Software Testing
Software TestingSoftware Testing
Software Testing
 
Boundary and equivalnce systematic test design
Boundary and equivalnce   systematic test designBoundary and equivalnce   systematic test design
Boundary and equivalnce systematic test design
 
software testing
 software testing software testing
software testing
 
Equivalence partitioning
Equivalence partitioningEquivalence partitioning
Equivalence partitioning
 
Equivalence partinioning and boundary value analysis
Equivalence partinioning and boundary value analysisEquivalence partinioning and boundary value analysis
Equivalence partinioning and boundary value analysis
 
Software Testing Life Cycle
Software Testing Life CycleSoftware Testing Life Cycle
Software Testing Life Cycle
 
Manual testing
Manual testingManual testing
Manual testing
 
Design & Analysis Of Algorithm
Design & Analysis Of AlgorithmDesign & Analysis Of Algorithm
Design & Analysis Of Algorithm
 
Software testing overview subbu
Software testing overview subbuSoftware testing overview subbu
Software testing overview subbu
 
Seminar on Software Testing
Seminar on Software TestingSeminar on Software Testing
Seminar on Software Testing
 
DESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMSDESIGN AND ANALYSIS OF ALGORITHMS
DESIGN AND ANALYSIS OF ALGORITHMS
 
Chapter 2 software development life cycle models
Chapter 2 software development life cycle modelsChapter 2 software development life cycle models
Chapter 2 software development life cycle models
 

Semelhante a Counting Sort Lowerbound

Semelhante a Counting Sort Lowerbound (20)

lecture 9
lecture 9lecture 9
lecture 9
 
lecture 10
lecture 10lecture 10
lecture 10
 
Sorting2
Sorting2Sorting2
Sorting2
 
Chapter 4 ds
Chapter 4 dsChapter 4 ds
Chapter 4 ds
 
Cis435 week06
Cis435 week06Cis435 week06
Cis435 week06
 
Linear sorting
Linear sortingLinear sorting
Linear sorting
 
Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0Algorithms with-java-advanced-1.0
Algorithms with-java-advanced-1.0
 
Daa chapter5
Daa chapter5Daa chapter5
Daa chapter5
 
lecture 11
lecture 11lecture 11
lecture 11
 
Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1Anlysis and design of algorithms part 1
Anlysis and design of algorithms part 1
 
sorting
sortingsorting
sorting
 
Data structure 8.pptx
Data structure 8.pptxData structure 8.pptx
Data structure 8.pptx
 
chapter1.pdf ......................................
chapter1.pdf ......................................chapter1.pdf ......................................
chapter1.pdf ......................................
 
Annotations.pdf
Annotations.pdfAnnotations.pdf
Annotations.pdf
 
CSE680-07QuickSort.pptx
CSE680-07QuickSort.pptxCSE680-07QuickSort.pptx
CSE680-07QuickSort.pptx
 
Q
QQ
Q
 
Dsa – data structure and algorithms sorting
Dsa – data structure and algorithms  sortingDsa – data structure and algorithms  sorting
Dsa – data structure and algorithms sorting
 
Merge sort
Merge sortMerge sort
Merge sort
 
Insersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in AlgoritmInsersion & Bubble Sort in Algoritm
Insersion & Bubble Sort in Algoritm
 
Unit6 C
Unit6 C Unit6 C
Unit6 C
 

Último

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introductionMaksud Ahmed
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...EduSkills OECD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxVishalSingh1417
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Krashi Coaching
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13Steve Thomason
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpinRaunakKeshri1
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Celine George
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...fonyou31
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 

Último (20)

Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
microwave assisted reaction. General introduction
microwave assisted reaction. General introductionmicrowave assisted reaction. General introduction
microwave assisted reaction. General introduction
 
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
Presentation by Andreas Schleicher Tackling the School Absenteeism Crisis 30 ...
 
Advance Mobile Application Development class 07
Advance Mobile Application Development class 07Advance Mobile Application Development class 07
Advance Mobile Application Development class 07
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
Kisan Call Centre - To harness potential of ICT in Agriculture by answer farm...
 
The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13The Most Excellent Way | 1 Corinthians 13
The Most Excellent Way | 1 Corinthians 13
 
Student login on Anyboli platform.helpin
Student login on Anyboli platform.helpinStudent login on Anyboli platform.helpin
Student login on Anyboli platform.helpin
 
Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17Advanced Views - Calendar View in Odoo 17
Advanced Views - Calendar View in Odoo 17
 
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
Ecosystem Interactions Class Discussion Presentation in Blue Green Lined Styl...
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 

Counting Sort Lowerbound

  • 1. Lower Bound for sorting Linear-Time Sorting Algorithms
  • 2. Sorting So Far Insertion sort: Easy to code Fast on small inputs (less than ~50 elements) Fast on nearly-sorted inputs O(n2 ) worst case O(n2 ) average (equally-likely inputs) case O(n2 ) reverse-sorted case
  • 3. Sorting So Far Merge sort: Divide-and-conquer: Split array in half Recursively sort sub arrays Linear-time merge step O(n lg n) worst case Doesn’t sort in place
  • 4. Sorting So Far Heap sort: Uses the very useful heap data structure Complete binary tree Heap property: parent key > children’s keys O(n lg n) worst case Sorts in place Fair amount of shuffling memory around
  • 5. Sorting So Far Quick sort: Divide-and-conquer: Partition array into two sub-arrays, recursively sort All of first sub-array < all of second sub-array No merge step needed! O(n lg n) average case Fast in practice O(n2 ) worst case Naïve implementation: worst case on sorted input Address this with randomized quicksort
  • 6. How Fast Can We Sort? We will provide a lower bound, then beat it How do you suppose we’ll beat it? First, an observation: all of the sorting algorithms so far are comparison sorts The only operation used to gain ordering information about a sequence is the pair-wise comparison of two elements Theorem: all comparison sorts are Ω(n lg n)
  • 7. Decision Trees Decision trees provide an abstraction of comparison sorts A decision tree represents the comparisons made by a comparison sort. Every thing else ignored What do the leaves represent? How many leaves must there be?
  • 8. Decision Trees Decision trees can model comparison sorts. For a given algorithm: One tree for each n Tree paths are all possible execution traces What’s the longest path in a decision tree for insertion sort? For merge sort? What is the asymptotic height of any decision tree for sorting n elements? Answer: Ω(n lg n) (now let’s prove it…)
  • 9. Lower Bound For Comparison Sorting Thm: Any decision tree that sorts n elements has height Ω(n lg n) What’s the minimum no. of leaves? What’s the maximum no. of leaves of a binary tree of height h? Clearly the minimum no of leaves is less than or equal to the maximum no. of leaves
  • 10.
  • 11. Lower Bound For Comparison Sorting So we have… n! ≤ 2h Taking logarithms: lg (n!) ≤ h Stirling’s approximation tells us: Thus: n e n n       >! n e n h       ≥ lg
  • 12. Lower Bound For Comparison Sorting So we have Thus the minimum height of a decision tree is Ω(n lg n) ( )nn ennn e n h n lg lglg lg Ω= −=       ≥
  • 13. Lower Bound For Comparison Sorts Thus the time to comparison sort n elements is Ω(n lg n) Corollary: Heapsort and Mergesort are asymptotically optimal comparison sorts But the name of this lecture is “Sorting in linear time”! How can we do better than Ω(n lg n)?
  • 14. Sorting In Linear Time Counting sort No comparisons between elements! But…depends on assumption about the numbers being sorted We assume numbers are in the range 1.. k The algorithm: Input: A[1..n], where A[j] ∈ {1, 2, 3, …, k} Output: B[1..n], sorted (notice: not sorting in place) Also: Array C[1..k] for auxiliary storage
  • 15. Counting Sort 1 CountingSort(A, B, k) 2 for i=1 to k 3 C[i]= 0; 4 for j=1 to n 5 C[A[j]] += 1; 6 for i=2 to k 7 C[i] = C[i] + C[i-1]; 8 for j=n downto 1 9 B[C[A[j]]] = A[j]; 10 C[A[j]] -= 1; Work through example: A={4 1 3 4 3}, k = 4
  • 16. Counting Sort 1 CountingSort(A, B, k) 2 for i=1 to k 3 C[i]= 0; 4 for j=1 to n 5 C[A[j]] += 1; 6 for i=2 to k 7 C[i] = C[i] + C[i-1]; 8 for j=n downto 1 9 B[C[A[j]]] = A[j]; 10 C[A[j]] -= 1; What will be the running time? Takes time O(k) Takes time O(n)
  • 17. Counting Sort Total time: O(n + k) Usually, k = O(n) Thus counting sort runs in O(n) time But sorting is Ω(n lg n)! No contradiction--this is not a comparison sort (in fact, there are no comparisons at all!) Notice that this algorithm is stable
  • 18.
  • 19. Counting Sort Cool! Why don’t we always use counting sort? Because it depends on range k of elements Could we use counting sort to sort 32 bit integers? Why or why not? Answer: no, k too large (232 = 4,294,967,296)
  • 20. David Luebke 20 08/01/13
  • 21. Radix Sort Intuitively, you might sort on the most significant digit, then the second msd, etc. Problem: lots of intermediate piles of cards (read: scratch arrays) to keep track of Key idea: sort the least significant digit first RadixSort(A, d) for i=1 to d StableSort(A) on digit i
  • 22. Radix Sort Can we prove it will work? Sketch of an inductive argument (induction on the number of passes): Assume lower-order digits {j: j<i}are sorted Show that sorting next digit i leaves array correctly sorted If two digits at position i are different, ordering numbers by that digit is correct (lower-order digits irrelevant) If they are the same, numbers are already sorted on the lower-order digits. Since we use a stable sort, the numbers stay in the right order
  • 23. Radix Sort What sort will we use to sort on digits? Counting sort is obvious choice: Sort n numbers on digits that range from 1..k Time: O(n + k) Each pass over n numbers with d digits takes time O(n+k), so total time O(dn+dk) When d is constant and k=O(n), takes O(n) time How many bits in a computer word?
  • 24. Radix Sort Problem: sort 1 million 64-bit numbers Treat as four-digit radix 216 numbers Can sort in just four passes with radix sort! Compares well with typical O(n lg n) comparison sort Requires approx lg n = 20 operations per number being sorted So why would we ever use anything but radix sort?
  • 25. Radix Sort In general, radix sort based on counting sort is Fast Asymptotically fast (i.e., O(n)) Simple to code A good choice To think about: Can radix sort be used on floating-point numbers?