Download presentation
Presentation is loading. Please wait.
Published byJulius Scott Modified over 9 years ago
1
Sorting
2
Why Sort? Put matching elements together –Uniqueness testing –Deleting duplicates –Frequency Counting –Set operations Prioritize Elements Reconstruct original order Efficient searching (binary search, pairs)
3
Sorting Algorithms (pp. 80-82) Insertion Sort –Least code, least data movement (inversions) Selection Sort –Conceptually simple, fewest swaps Quick Sort –Fastest –Needs careful implementation –Partition algorithm useful on its own
4
Comparison Functions Use with generalized sorting algorithms Stable Sort –Sort criteria separately (most important last) Unstable Sort –Previously sorted not necessarily still in order –One comparison function handles all criteria
5
Sorting in C++ (STL) Library functions sort and stable_sort –Iterator bg (beginning of list) –Iterator end (end of list) –Optional BinaryPredicate (default <=) Function that takes two items and returns true if they are in order
6
Sorting in Java In java.util.Arrays –Array of Objects (Object[] a) –Optional Comparator (default <=)
7
Search Sequential Search Binary Search –Tricky to get right under pressure Consider stopping condition –Library functions C++ STL: bsearch Java: binarySearch (see pp. 84-85)
8
Generalizing Search Sequential –Foreach element If ( correct(element) ) process and break Binary –While (remaining list not empty) If (too-high (middle-of-list)) –Cut off bottom half Else if (too-low (middle-of-list)) –Cut off top half Else process and break
9
Notes on Binary Search Generalized functions “too-high” and “too- low” might evaluate criteria other than a value –E.g. outcome of function with a given parameter If you can estimate a location better than the middle, use it! (phone book search)
Similar presentations
© 2024 SlidePlayer.com. Inc.
All rights reserved.