chapter 18

Post on 20-Nov-2014

518 Views

Category:

Technology

2 Downloads

Preview:

Click to see full reader

DESCRIPTION

 

TRANSCRIPT

Sorting

Chapter 18

18

Creating Sortable ObjectsObjects are sortable when they implement the Comparable interface.

Must implement compareTo() method

Programmer must decide how to compare objects.

18

Sorting ArraysTreeSet collections are sorted by default.Arrays class includes a sort() method.

Items in array must be sortable (implement the Comparable interface).

18

Sorting AlgorithmsSortable interface

Provides framework for sort classesDefines what it means to be sortable

SortList classHolds the items in the list in an internal ArrayListTracks:

Number of items in the listNumber of comparisonsNumber of exchangesIndicates whether algorithm steps should be displayed

18

The Nested SortItem ClassSortItem class:

Implements Comparable interface

Uses the compareTo() method to compare current object to an object passed in

Uses the exchangeValues() method to exchange values when required

18

Sorting Algorithms

SortDriver class:Creates a sort object and submits a list to test the algorithmWill be modified several times as new sort algorithm classes are created

SortAlgorithm class:Abstract base class (used to derive all sort algorithm classes)Provides common methods used by all the sort algorithms

18

Insertion SortRecursive 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 SortThe 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 SortSelection 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 SortBubble 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

QuicksortMost widely used sort methodPartitions the list

Use “pivot” to create right and left sideMove item from left to right if larger than pivotMove item from right to left if smaller than pivotEach side is then partitioned and algorithm recurses until list is sorted

18Comparison of Sort

AlgorithmsDirect comparison using random values

top related