SlideShare una empresa de Scribd logo
1 de 16
Descargar para leer sin conexión
Week 8
Searching and sorting
In this lecture we cover two fundamental algorithmic problems: searching
and sorting. These are not problems you will like ever need to solve yourself
nor are they algorithms you will find yourself implementing. They are already
implemented in the programming environment you use unless you start
entirely from scratch. But the problems are easy to understand so they are a
good place to exercise thinking about algorithms.
Searching
The search problem is this: you have a collection of objects and you want to
check if a given element is among them. We often call the element a key.
The reason we call it a key is that we sometimes have information
associated with the elements—we call those values—and we map keys to
values. For example, in a phone book—back when we had such beasts—
you would have names associated with numbers. The names are the keys,
the phone numbers the values. You search for the key because you want to
find the associated value.
Linear search
The simplest way to search is to look at each element in turn, compare the
keys, and if one matches, you get the key-value pair. In the example in the
book, we just determine if a key is found in a list of numbers, but getting a
value associated with a key is just as easy. You can try to implement that
yourself. Because we simply run through each element in turn, we call this a
linear search.
Linear search
• What is the best-case running time?

• What is the worst-case running time?

• What is the memory usage?

• Which assumptions have we made about the keys and
how the data is represented?
To understand linear search, try to answer these questions.
Binary search
When you look up names in a phone book, you do not start at the beginning
and search each name in turn. You exploit that the names are sorted
alphabetically (we also call this lexically sorted, but that is just a different
name for the samething). In a phone book you have some intuition about
where a name is likely found so you start there, but in general you would
start in the middel. If you cut the search-space in half every time you do not
find the key, you have binary search.
Binary search
• What is the best-case running time?

• What is the worst-case running time?

• What is the memory usage?

• Which assumptions have we made about the keys and
how the data is represented?
To understand the difference between linear search and binary search, try to
answer these questions.
Sorting
The sorting problem is this: given a collection of element, order them with
respect to their keys.
Properties of sorting
algorithms
We often classify sorting algorithms according to these properties. They are
defined in the book, but can you explain them in your own words?
Comparison-based
sorting
Another classification of sorting algorithms is whether they are comparison
based or not. Comparison-based means that we can compare keys to
determine which is smaller than anther, but we do not make any other
assumptions. (The specific algorithms might need more assumptions,
though, but it is the only assumption we make about the keys).
Insertion sort
With insertion sort, you have a list of sorted elements and a list of those you
have yet to sort. You pick one of the unsorted elements in turn, and move it
to where it belongs in the sorted list. You might have to move some of the
sorted elements if they are larger than the new one.
Here, the blue underline indicates the already-sorted elements, the orange
arrow shows where we compare to keys, and the red arrows where we swap
two elements.
• Termination: Trivial — nested finite for-loops

• Correctness:
We use these two invariants to prove correctness. Can you argue why they
guarantee correctness when the algorithm finishes? Can you show why the
loop-body guarantees the invariants?
Insertion sort
• Which assumptions have we made?

• Is it stable?

• What is the worst-case number of comparisons?

• What is the best-case number of comparisons?

• What is the worst-case number of swaps?

• What is the best-case number of swaps?
Try to answer these questions. The answers are not the same for all the
algorithms, so think about them.
Selection sort
With selection sort you also have a list of sorted elements and a list of keys
that are yet to be sorted. This time, though, you ensure that the sorted
elements are smaller than (or equal to) the smallest in the set of elements we
haven’t sorted yet. In each iteration, we pick the smallest of those keys and
add it to the sorted list.
• Termination: Trivial — nested finite for-loops

• Correctness:
Can you argue why this invariant is guaranteed by the algorithm and why it
ensure correctness?
Selection sort
• Which assumptions have we made?

• Is it stable?

• What is the worst-case number of comparisons?

• What is the best-case number of comparisons?

• What is the worst-case number of swaps?

• What is the best-case number of swaps?
Now, try to answer these questions. Where do you get different answers
than for insertion sort?
Bubble sort
With bubble sort we do not have a collection of sorted and a collection of
not-sorted elements. Instead, we repeatedly swap pairs that are out order,
i.e. pairs where the first is larger than the second.
• Termination: Not trivial! (But wait for it…)

• Correctness:
j is # outer iterations
The invariants are a bit more complicated, but try to argue that they are
satisfied and that they ensure correctness.

• Termination:

• Correctness:
j is # outer iterations
While j is only used for the analysis,

and not a real "for-loop" variable we

can use it in the termination function:

t(j) = n - j
Since we do not use simple for-loops in bubble sort (at least for the
outermost loop), we need to prove that the algorithm terminates. We use a
“virtual” variable, j, for this. Can you argue why this works and guarantees
termination?
Bubble sort
• Which assumptions have we made?

• Is it stable?

• What is the worst-case number of comparisons?

• What is the best-case number of comparisons?

• What is the worst-case number of swaps?

• What is the best-case number of swaps?
Again, try to answer these questions.
Index-based sorting
With index-based sorting algorithms we make stronger assumptions about
the keys. We assume that they can be used as indices into an array—an
array, here, is just like a Python list, but in algorithms we make some
distinctions between “arrays” and “lists”. Lists are sequences we can iterate
through; arrays are sequences with random access. Python lists are both.
Count sort
Count sort is the simplest of these algorithms. We simply count how often
we see each key, and then output a list that has the right number of each
key in order.
Bucket sort
If we need to distinguish between the keys—for example if we associated
values with them—then we have bucket sort. Here I have just used colours
as the values. With bucket sort we need to keep track of the values. To get a
stable sort, we must output the key-value pairs in the same order as we saw
them in the input. How do you do that with Python lists?
Bucket sort
• Which assumptions have we made?

• Is it stable?

• What is the best- and worst-case running time?

• What is the best- and worst-case memory usage?
Answer these questions.
Radix sort
We can use radix sort when we have multiple keys that we can use in a
bucket sort, or when we can split our keys into sub-keys we can use in a
bucket sort. The order in which we sort the different keys matter—can you
explain why? The bucket sort must be stable. Can you explain why?
Exercises!
Time to put searching
and sorting into practice

Más contenido relacionado

Similar a Chapter 5 searching and sorting handouts with notes

Searching Sorting
Searching SortingSearching Sorting
Searching Sorting
guest2cb109
 
Foundation_Logic_1.pptx discrete mathematics
Foundation_Logic_1.pptx discrete mathematicsFoundation_Logic_1.pptx discrete mathematics
Foundation_Logic_1.pptx discrete mathematics
SherwinSangalang3
 
Please Please Please Read the instructions and do everything li.docx
Please Please Please Read the instructions and do everything li.docxPlease Please Please Read the instructions and do everything li.docx
Please Please Please Read the instructions and do everything li.docx
tienmixon
 

Similar a Chapter 5 searching and sorting handouts with notes (20)

4.1 sequentioal search
4.1 sequentioal search4.1 sequentioal search
4.1 sequentioal search
 
CPP12 - Algorithms
CPP12 - AlgorithmsCPP12 - Algorithms
CPP12 - Algorithms
 
Sorting algorithms
Sorting algorithmsSorting algorithms
Sorting algorithms
 
arrays in c
arrays in carrays in c
arrays in c
 
Linear Search
Linear SearchLinear Search
Linear Search
 
Searching Sorting
Searching SortingSearching Sorting
Searching Sorting
 
Foundation_Logic_1.pptx discrete mathematics
Foundation_Logic_1.pptx discrete mathematicsFoundation_Logic_1.pptx discrete mathematics
Foundation_Logic_1.pptx discrete mathematics
 
Chapter 5 searching and sorting
Chapter 5   searching and sortingChapter 5   searching and sorting
Chapter 5 searching and sorting
 
Chapter 5 searching and sorting handouts
Chapter 5   searching and sorting handoutsChapter 5   searching and sorting handouts
Chapter 5 searching and sorting handouts
 
SEARCHING
SEARCHINGSEARCHING
SEARCHING
 
Chapter 3 introduction to algorithms handouts (with notes)
Chapter 3 introduction to algorithms handouts (with notes)Chapter 3 introduction to algorithms handouts (with notes)
Chapter 3 introduction to algorithms handouts (with notes)
 
Lecture_Oct26.pptx
Lecture_Oct26.pptxLecture_Oct26.pptx
Lecture_Oct26.pptx
 
Heuristic search-in-artificial-intelligence
Heuristic search-in-artificial-intelligenceHeuristic search-in-artificial-intelligence
Heuristic search-in-artificial-intelligence
 
Introduction to Algorithms
Introduction to AlgorithmsIntroduction to Algorithms
Introduction to Algorithms
 
SORTING techniques.pptx
SORTING techniques.pptxSORTING techniques.pptx
SORTING techniques.pptx
 
Spreadsheets are graphs too: Using Neo4J as backend to store spreadsheet info...
Spreadsheets are graphs too: Using Neo4J as backend to store spreadsheet info...Spreadsheets are graphs too: Using Neo4J as backend to store spreadsheet info...
Spreadsheets are graphs too: Using Neo4J as backend to store spreadsheet info...
 
Sorting
SortingSorting
Sorting
 
Please Please Please Read the instructions and do everything li.docx
Please Please Please Read the instructions and do everything li.docxPlease Please Please Read the instructions and do everything li.docx
Please Please Please Read the instructions and do everything li.docx
 
Rahat & juhith
Rahat & juhithRahat & juhith
Rahat & juhith
 
Algorithms
Algorithms Algorithms
Algorithms
 

Más de mailund

Ku 05 08 2009
Ku 05 08 2009Ku 05 08 2009
Ku 05 08 2009
mailund
 
Association mapping using local genealogies
Association mapping using local genealogiesAssociation mapping using local genealogies
Association mapping using local genealogies
mailund
 
Neural Networks
Neural NetworksNeural Networks
Neural Networks
mailund
 
Probability And Stats Intro
Probability And Stats IntroProbability And Stats Intro
Probability And Stats Intro
mailund
 
Probability And Stats Intro2
Probability And Stats Intro2Probability And Stats Intro2
Probability And Stats Intro2
mailund
 
Linear Regression Ex
Linear Regression ExLinear Regression Ex
Linear Regression Ex
mailund
 
Course Introduction
Course IntroductionCourse Introduction
Course Introduction
mailund
 
Linear Classification
Linear ClassificationLinear Classification
Linear Classification
mailund
 
Linear Regression
Linear RegressionLinear Regression
Linear Regression
mailund
 

Más de mailund (20)

Chapter 9 divide and conquer handouts with notes
Chapter 9   divide and conquer handouts with notesChapter 9   divide and conquer handouts with notes
Chapter 9 divide and conquer handouts with notes
 
Chapter 9 divide and conquer handouts
Chapter 9   divide and conquer handoutsChapter 9   divide and conquer handouts
Chapter 9 divide and conquer handouts
 
Chapter 9 divide and conquer
Chapter 9   divide and conquerChapter 9   divide and conquer
Chapter 9 divide and conquer
 
Chapter 7 recursion handouts with notes
Chapter 7   recursion handouts with notesChapter 7   recursion handouts with notes
Chapter 7 recursion handouts with notes
 
Chapter 7 recursion handouts
Chapter 7   recursion handoutsChapter 7   recursion handouts
Chapter 7 recursion handouts
 
Chapter 7 recursion
Chapter 7   recursionChapter 7   recursion
Chapter 7 recursion
 
Chapter 4 algorithmic efficiency handouts (with notes)
Chapter 4   algorithmic efficiency handouts (with notes)Chapter 4   algorithmic efficiency handouts (with notes)
Chapter 4 algorithmic efficiency handouts (with notes)
 
Chapter 4 algorithmic efficiency handouts
Chapter 4   algorithmic efficiency handoutsChapter 4   algorithmic efficiency handouts
Chapter 4 algorithmic efficiency handouts
 
Chapter 4 algorithmic efficiency
Chapter 4   algorithmic efficiencyChapter 4   algorithmic efficiency
Chapter 4 algorithmic efficiency
 
Chapter 3 introduction to algorithms slides
Chapter 3 introduction to algorithms slidesChapter 3 introduction to algorithms slides
Chapter 3 introduction to algorithms slides
 
Chapter 3 introduction to algorithms handouts
Chapter 3 introduction to algorithms handoutsChapter 3 introduction to algorithms handouts
Chapter 3 introduction to algorithms handouts
 
Ku 05 08 2009
Ku 05 08 2009Ku 05 08 2009
Ku 05 08 2009
 
Association mapping using local genealogies
Association mapping using local genealogiesAssociation mapping using local genealogies
Association mapping using local genealogies
 
Neural Networks
Neural NetworksNeural Networks
Neural Networks
 
Probability And Stats Intro
Probability And Stats IntroProbability And Stats Intro
Probability And Stats Intro
 
Probability And Stats Intro2
Probability And Stats Intro2Probability And Stats Intro2
Probability And Stats Intro2
 
Linear Regression Ex
Linear Regression ExLinear Regression Ex
Linear Regression Ex
 
Course Introduction
Course IntroductionCourse Introduction
Course Introduction
 
Linear Classification
Linear ClassificationLinear Classification
Linear Classification
 
Linear Regression
Linear RegressionLinear Regression
Linear Regression
 

Último

(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
Scintica Instrumentation
 
LUNULARIA -features, morphology, anatomy ,reproduction etc.
LUNULARIA -features, morphology, anatomy ,reproduction etc.LUNULARIA -features, morphology, anatomy ,reproduction etc.
LUNULARIA -features, morphology, anatomy ,reproduction etc.
Silpa
 
The Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptxThe Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptx
seri bangash
 
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune WaterworldsBiogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Sérgio Sacani
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
development of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virusdevelopment of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virus
NazaninKarimi6
 
Porella : features, morphology, anatomy, reproduction etc.
Porella : features, morphology, anatomy, reproduction etc.Porella : features, morphology, anatomy, reproduction etc.
Porella : features, morphology, anatomy, reproduction etc.
Silpa
 
THE ROLE OF BIOTECHNOLOGY IN THE ECONOMIC UPLIFT.pptx
THE ROLE OF BIOTECHNOLOGY IN THE ECONOMIC UPLIFT.pptxTHE ROLE OF BIOTECHNOLOGY IN THE ECONOMIC UPLIFT.pptx
THE ROLE OF BIOTECHNOLOGY IN THE ECONOMIC UPLIFT.pptx
ANSARKHAN96
 
Digital Dentistry.Digital Dentistryvv.pptx
Digital Dentistry.Digital Dentistryvv.pptxDigital Dentistry.Digital Dentistryvv.pptx
Digital Dentistry.Digital Dentistryvv.pptx
MohamedFarag457087
 

Último (20)

(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
(May 9, 2024) Enhanced Ultrafast Vector Flow Imaging (VFI) Using Multi-Angle ...
 
LUNULARIA -features, morphology, anatomy ,reproduction etc.
LUNULARIA -features, morphology, anatomy ,reproduction etc.LUNULARIA -features, morphology, anatomy ,reproduction etc.
LUNULARIA -features, morphology, anatomy ,reproduction etc.
 
Clean In Place(CIP).pptx .
Clean In Place(CIP).pptx                 .Clean In Place(CIP).pptx                 .
Clean In Place(CIP).pptx .
 
Dr. E. Muralinath_ Blood indices_clinical aspects
Dr. E. Muralinath_ Blood indices_clinical  aspectsDr. E. Muralinath_ Blood indices_clinical  aspects
Dr. E. Muralinath_ Blood indices_clinical aspects
 
Grade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its FunctionsGrade 7 - Lesson 1 - Microscope and Its Functions
Grade 7 - Lesson 1 - Microscope and Its Functions
 
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry
GBSN - Biochemistry (Unit 2) Basic concept of organic chemistry
 
The Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptxThe Mariana Trench remarkable geological features on Earth.pptx
The Mariana Trench remarkable geological features on Earth.pptx
 
CURRENT SCENARIO OF POULTRY PRODUCTION IN INDIA
CURRENT SCENARIO OF POULTRY PRODUCTION IN INDIACURRENT SCENARIO OF POULTRY PRODUCTION IN INDIA
CURRENT SCENARIO OF POULTRY PRODUCTION IN INDIA
 
Zoology 5th semester notes( Sumit_yadav).pdf
Zoology 5th semester notes( Sumit_yadav).pdfZoology 5th semester notes( Sumit_yadav).pdf
Zoology 5th semester notes( Sumit_yadav).pdf
 
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate ProfessorThyroid Physiology_Dr.E. Muralinath_ Associate Professor
Thyroid Physiology_Dr.E. Muralinath_ Associate Professor
 
Chemistry 5th semester paper 1st Notes.pdf
Chemistry 5th semester paper 1st Notes.pdfChemistry 5th semester paper 1st Notes.pdf
Chemistry 5th semester paper 1st Notes.pdf
 
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRings
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRingsTransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRings
TransientOffsetin14CAftertheCarringtonEventRecordedbyPolarTreeRings
 
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and SpectrometryFAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
FAIRSpectra - Enabling the FAIRification of Spectroscopy and Spectrometry
 
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune WaterworldsBiogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
Biogenic Sulfur Gases as Biosignatures on Temperate Sub-Neptune Waterworlds
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Gwalior ❤CALL GIRL 84099*07087 ❤CALL GIRLS IN Gwalior ESCORT SERVICE❤CALL GIRL
Gwalior ❤CALL GIRL 84099*07087 ❤CALL GIRLS IN Gwalior ESCORT SERVICE❤CALL GIRLGwalior ❤CALL GIRL 84099*07087 ❤CALL GIRLS IN Gwalior ESCORT SERVICE❤CALL GIRL
Gwalior ❤CALL GIRL 84099*07087 ❤CALL GIRLS IN Gwalior ESCORT SERVICE❤CALL GIRL
 
development of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virusdevelopment of diagnostic enzyme assay to detect leuser virus
development of diagnostic enzyme assay to detect leuser virus
 
Porella : features, morphology, anatomy, reproduction etc.
Porella : features, morphology, anatomy, reproduction etc.Porella : features, morphology, anatomy, reproduction etc.
Porella : features, morphology, anatomy, reproduction etc.
 
THE ROLE OF BIOTECHNOLOGY IN THE ECONOMIC UPLIFT.pptx
THE ROLE OF BIOTECHNOLOGY IN THE ECONOMIC UPLIFT.pptxTHE ROLE OF BIOTECHNOLOGY IN THE ECONOMIC UPLIFT.pptx
THE ROLE OF BIOTECHNOLOGY IN THE ECONOMIC UPLIFT.pptx
 
Digital Dentistry.Digital Dentistryvv.pptx
Digital Dentistry.Digital Dentistryvv.pptxDigital Dentistry.Digital Dentistryvv.pptx
Digital Dentistry.Digital Dentistryvv.pptx
 

Chapter 5 searching and sorting handouts with notes

  • 1. Week 8 Searching and sorting In this lecture we cover two fundamental algorithmic problems: searching and sorting. These are not problems you will like ever need to solve yourself nor are they algorithms you will find yourself implementing. They are already implemented in the programming environment you use unless you start entirely from scratch. But the problems are easy to understand so they are a good place to exercise thinking about algorithms. Searching
  • 2. The search problem is this: you have a collection of objects and you want to check if a given element is among them. We often call the element a key. The reason we call it a key is that we sometimes have information associated with the elements—we call those values—and we map keys to values. For example, in a phone book—back when we had such beasts— you would have names associated with numbers. The names are the keys, the phone numbers the values. You search for the key because you want to find the associated value.
  • 3. Linear search The simplest way to search is to look at each element in turn, compare the keys, and if one matches, you get the key-value pair. In the example in the book, we just determine if a key is found in a list of numbers, but getting a value associated with a key is just as easy. You can try to implement that yourself. Because we simply run through each element in turn, we call this a linear search. Linear search • What is the best-case running time? • What is the worst-case running time? • What is the memory usage? • Which assumptions have we made about the keys and how the data is represented? To understand linear search, try to answer these questions.
  • 4. Binary search When you look up names in a phone book, you do not start at the beginning and search each name in turn. You exploit that the names are sorted alphabetically (we also call this lexically sorted, but that is just a different name for the samething). In a phone book you have some intuition about where a name is likely found so you start there, but in general you would start in the middel. If you cut the search-space in half every time you do not find the key, you have binary search. Binary search • What is the best-case running time? • What is the worst-case running time? • What is the memory usage? • Which assumptions have we made about the keys and how the data is represented? To understand the difference between linear search and binary search, try to answer these questions.
  • 5. Sorting The sorting problem is this: given a collection of element, order them with respect to their keys. Properties of sorting algorithms We often classify sorting algorithms according to these properties. They are defined in the book, but can you explain them in your own words?
  • 6. Comparison-based sorting Another classification of sorting algorithms is whether they are comparison based or not. Comparison-based means that we can compare keys to determine which is smaller than anther, but we do not make any other assumptions. (The specific algorithms might need more assumptions, though, but it is the only assumption we make about the keys). Insertion sort With insertion sort, you have a list of sorted elements and a list of those you have yet to sort. You pick one of the unsorted elements in turn, and move it to where it belongs in the sorted list. You might have to move some of the sorted elements if they are larger than the new one.
  • 7. Here, the blue underline indicates the already-sorted elements, the orange arrow shows where we compare to keys, and the red arrows where we swap two elements.
  • 8. • Termination: Trivial — nested finite for-loops • Correctness: We use these two invariants to prove correctness. Can you argue why they guarantee correctness when the algorithm finishes? Can you show why the loop-body guarantees the invariants? Insertion sort • Which assumptions have we made? • Is it stable? • What is the worst-case number of comparisons? • What is the best-case number of comparisons? • What is the worst-case number of swaps? • What is the best-case number of swaps? Try to answer these questions. The answers are not the same for all the algorithms, so think about them.
  • 9. Selection sort With selection sort you also have a list of sorted elements and a list of keys that are yet to be sorted. This time, though, you ensure that the sorted elements are smaller than (or equal to) the smallest in the set of elements we haven’t sorted yet. In each iteration, we pick the smallest of those keys and add it to the sorted list.
  • 10. • Termination: Trivial — nested finite for-loops • Correctness: Can you argue why this invariant is guaranteed by the algorithm and why it ensure correctness? Selection sort • Which assumptions have we made? • Is it stable? • What is the worst-case number of comparisons? • What is the best-case number of comparisons? • What is the worst-case number of swaps? • What is the best-case number of swaps? Now, try to answer these questions. Where do you get different answers than for insertion sort?
  • 11. Bubble sort With bubble sort we do not have a collection of sorted and a collection of not-sorted elements. Instead, we repeatedly swap pairs that are out order, i.e. pairs where the first is larger than the second.
  • 12. • Termination: Not trivial! (But wait for it…) • Correctness: j is # outer iterations The invariants are a bit more complicated, but try to argue that they are satisfied and that they ensure correctness. • Termination: • Correctness: j is # outer iterations While j is only used for the analysis, and not a real "for-loop" variable we can use it in the termination function: t(j) = n - j Since we do not use simple for-loops in bubble sort (at least for the outermost loop), we need to prove that the algorithm terminates. We use a “virtual” variable, j, for this. Can you argue why this works and guarantees termination?
  • 13. Bubble sort • Which assumptions have we made? • Is it stable? • What is the worst-case number of comparisons? • What is the best-case number of comparisons? • What is the worst-case number of swaps? • What is the best-case number of swaps? Again, try to answer these questions. Index-based sorting With index-based sorting algorithms we make stronger assumptions about the keys. We assume that they can be used as indices into an array—an array, here, is just like a Python list, but in algorithms we make some distinctions between “arrays” and “lists”. Lists are sequences we can iterate through; arrays are sequences with random access. Python lists are both.
  • 14. Count sort Count sort is the simplest of these algorithms. We simply count how often we see each key, and then output a list that has the right number of each key in order. Bucket sort If we need to distinguish between the keys—for example if we associated values with them—then we have bucket sort. Here I have just used colours as the values. With bucket sort we need to keep track of the values. To get a stable sort, we must output the key-value pairs in the same order as we saw them in the input. How do you do that with Python lists?
  • 15. Bucket sort • Which assumptions have we made? • Is it stable? • What is the best- and worst-case running time? • What is the best- and worst-case memory usage? Answer these questions. Radix sort We can use radix sort when we have multiple keys that we can use in a bucket sort, or when we can split our keys into sub-keys we can use in a bucket sort. The order in which we sort the different keys matter—can you explain why? The bucket sort must be stable. Can you explain why?
  • 16. Exercises! Time to put searching and sorting into practice