chapter 18

12
Sorting Chapter 18

Upload: graham-royce

Post on 20-Nov-2014

518 views

Category:

Technology


2 download

DESCRIPTION

 

TRANSCRIPT

Page 1: Chapter 18

Sorting

Chapter 18

Page 2: 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.

Page 3: Chapter 18

18

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

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

Page 4: Chapter 18

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

Page 5: Chapter 18

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

Page 6: Chapter 18

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

Page 7: Chapter 18

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.

Page 8: Chapter 18

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

Page 9: Chapter 18

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

Page 10: Chapter 18

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

Page 11: Chapter 18

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

Page 12: Chapter 18

18Comparison of Sort

AlgorithmsDirect comparison using random values