Professional Documents
Culture Documents
2B Sorts
2B Sorts
2B Sorts
Algorithms
Unit 2
CPRG304 – Object-Oriented
Programming III
• Internal Sorting
• The whole collection of data resides in memory (RAM)
• Faster access = faster sorting
• External Sorting
• Data resides in both memory and secondary storage (hard
disk)
• Slower due to transfer of data to/from disk
• We will not cover these types of sorts in this course
Insertion Sort
• Successively read each value and insert it into its
correct position in an array
• Every much like you would sort a hand of cards!
• https://www.youtube.com/watch?v=DFG-XuyPYUQ&ab_channel=CS50
Complexity of Insertion Sort
• Time complexity – O(n2)
• Nested loop
• Outer loop is the element to be sorted in the list
• Inner loop iterates through sub-list to find the current element’s place
• https://www.youtube.com/watch?v=f8hXR_Hvybo&ab_channel=CS50
Complexity of Selection Sort
• Time complexity – O(n2)
• Nested loop
• Outer loop iterated to find smallest element of in the list for the pass
• Inner loop iterated to does the comparision and swap
• https://www.hackerearth.com/practice/algorithms/sorting/bubble-sort/visualiz
e/
Complexity of Bubble Sort
• Time complexity – O(n2)
• Nested loops
• Outer loop to determine do a pass for all n elements in the list
• Inner loop to compare elements and swap the largest ones
• The first iteration of the inner loop will iterate through all n elements
• https://www.youtube.com/watch?v=EeQ8pwjQxTM&ab_channel=CS50
Time Complexity of Merge Sort
• Merge Sort (combination)
• Time Complexity: O(n log n)
• Space Complexity: O(n)
• First element:
• Simple, no overhead
• Still O(n2) if collection is sorted
• Random selection:
• Safe in almost all situations, but calculating a random number can be costly
• Median element:
• Optimal, but impractical to implement
Median-of-3
• Value of the median element out the elements in first
position, middle position and last position
• If collection is not odd-number sized, just pick the element
before or after
0 1 2 3 4 5 6 7 8 9
a
• E.g. sort a[0], a[4], a[9], pivot = middle value
• Easy and fast
• A good compromise to finding the actual median
• Works even if the collection is already sorted
Non-Comparative Sorts
• Comparative sorts can perform at best O(n log n)
• O(log n) comparisons and O(n) merge, shifts or swaps
• Non-comparative = no comparisons
• No more O(log n) for comparing elements!
• Also know distribution sorts
• Implementation:
References
• Data Structures and Abstractions with Java, 5th edition,
2019, Frank M. Carrano, Pearson.
• Big Java: Early Objects, 7th edition, 2018, Cay S.
Horstmann, Wiley.