Sorting. Why Sort? Put matching elements together –Uniqueness testing –Deleting duplicates...
-
Upload
julius-scott -
Category
Documents
-
view
216 -
download
2
Transcript of Sorting. Why Sort? Put matching elements together –Uniqueness testing –Deleting duplicates...
Sorting
Why Sort?
• Put matching elements together– Uniqueness testing– Deleting duplicates– Frequency Counting– Set operations
• Prioritize Elements• Reconstruct original order• Efficient searching (binary search, pairs)
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
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
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
Sorting in Java
• In java.util.Arrays– Array of Objects (Object[] a)– Optional Comparator (default <=)
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)
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
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)