Chapter 18 Sorting 18 Creating Sortable Objects are

Chapter 18 Sorting

18 Creating Sortable Objects are sortable when they implement the Comparable interface. Must implement compare. To() method Programmer must decide how to compare objects.

18 Sorting Arrays Tree. Set collections are sorted by default. Arrays class includes a sort() method. Items in array must be sortable (implement the Comparable interface).

18 Sorting Algorithms Sortable interface Provides framework for sort classes Defines what it means to be sortable Sort. List class Holds the items in the list in an internal Array. List Tracks: Number of items in the list Number of comparisons Number of exchanges Indicates whether algorithm steps should be displayed

18 The Nested Sort. Item Class Sort. Item class: Implements Comparable interface Uses the compare. To() method to compare current object to an object passed in Uses the exchange. Values() method to exchange values when required

18 Sorting Algorithms Sort. Driver class: Creates a sort object and submits a list to test the algorithm Will be modified several times as new sort algorithm classes are created Sort. Algorithm class: Abstract base class (used to derive all sort algorithm classes) Provides common methods used by all the sort algorithms

18 Insertion Sort Recursive insertion: Compare new object to each object in the list until you find one of lesser value. Requires a lot of comparisons and exchanges.

18 Shell Sort The shell sort is a variation on the insertion sort. Divides list into smaller sublists Sorts each sublist individually Then sorts sublists together Requires many comparisons, but fewer exchanges

18 Selection Sort Selection sort: Scans list to find lowest value then moves it to the left Repeat to find next lowest value Many comparisons with minimal exchanges

18 Bubble Sort Bubble sort: Compares each item to its neighbor and exchanges if necessary Largest items “bubble” to the top Poor performance due to many comparisons and many exchanges

18 Quicksort Most widely used sort method Partitions the list Use “pivot” to create right and left side Move item from left to right if larger than pivot Move item from right to left if smaller than pivot Each side is then partitioned and algorithm recurses until list is sorted

18 Comparison of Sort Algorithms Direct comparison using random values
- Slides: 12