L2 Sorting
L2 Sorting
LECTURE 2
Sorting
Reference links:
https://cs.nyu.edu/courses/fall17/CSCI-UA.0102-
007/notes.php
https://www.comp.nus.edu.sg/~stevenha/cs2040.html
https://visualgo.net/en/sorting
3
Lecture outline
❑ Why sorting?
❑ Sorting applications
❑ Simple sort algorithms
▪ Bubble Sort; Selection Sort; Insertion Sort; Shuffle sort
❑ Effective sort algorithms
▪ Quick Sort; Merge Sort
❑ Some other algorithms
▪ Radix Sort, Heap Sort
❑ Execirses
3
Why sorting?
Sorting
Sorting
.
Sorting Applications
Bubble Sort
Bubble Sort : Idea
i
Bubble Sort : Analysis
❑ Worst-case
▪ input is in descending order
▪ running-time remains the same: O(n2)
❑ Best-case
▪ input is already in ascending order
❑ Average-case
▪ input is in disorder: O(n2)
Simple Sorting Agorithms
Selection Sort
Selection Sort : Idea
Insertion Sort
Insertion Sort : Idea
Shuffle Sort
Shuffle Sort : Idea
❑ Idea:
▪ Generate a random real number for each array entry,
then sort the array (O(n2))
▪ For each array entry, swap it with an entry at random
position (O(n))
Shuffle Sort : Implementation
Quick Sort
Divide and Conquer
Merge Sort
Merge Sort : Idea
❑ Conquer Step:
▪ Merge the two halves to form a sorted array
Merge Sort : Illustration
❑ Note:
- mergeSort() is a recursive function
- low >= high is the base case, i.e the array has 0 or 1 item
Merge Sort : An example
Merge Sort : An example
❑ Question:
- Why do we need a temporary array b[ ]?
Merge Sort : Analysis
❑ Pros:
▪ The performance is guaranteed, i.e. unaffected by,original
ordering of the input.
▪ Suitable for extremely large number of inputs.
▪ Can operate on the input portion by portion
❑ Cons:
▪ Not easy to implement
▪ Requires additional storage during merging operation
▪ O(n) extra memory storage needed
Properties of Sorting
In-Place Sorting
Stable Sorting
In-Place Sorting
❑ Example:
▪ Student names have been sorted into alphabetical order
▪ If it is sorted again according to tutorial group number:
▪ A stable sorting algorithm will make all within the same group to
appear in alphabetical order
Sorting Algorithms: Summary
Algorithm Worst Case Best Case In-place Stable