Chapter 18

Sorting and Searching


Chapter Goals

Sorting an Array of Integers

File SelectionSorter.java

File SelectionSortTest.java

File ArrayUtil.java

Profiling the Selection Sort Algorithm

File StopWatch.java

 

File SelectionSortTimer

Time Taken By Selection Sort on Various Size Arrays

Doubling the size of the array more than doubles the time needed to sort it

Table Selection Sort Times

Graph Graph of Selection Sort Time

 

Analyzing the Performance of Selection Sort Algorithm

Merge Sort

File MergeSorter.java

File MergeSortTest.java

Merge Sort vs Selection Sort

Merge vs Selection Sort

Merge Sort Timing Vs Selection Sort

Merge sort - rectangles
Selection sort - circles

Graph of Merge vs Selection Sort

Analyzing Merge Sort Algorithm

Merge Sort Vs Selection Sort

Sorting in a Java Program

Linear Search

File LinearSearcher.java

File LinearSearchTest.java

Binary Search

File BinarySearcher.java

File BinarySearchTest.java

Searching a Sorted Array in a Java Program

Sorting and Searching Arrays of Objects

CompareTo for BankAccount

public class BankAccount
{
   . . . 
   public int compareTo(Object otherObject)
   {
      BankAccount other = (BankAccount)otherObject;
      if (balance < other.balance) return -1;
      if (balance == other.balance return 0;
      return 1;
   }
   . . . 
}

CompareTo Method

The method implementation must define a total ordering relationship

Sorting and Searching Arrays of Objects Using Comparator

Comparator Class for Coins

public class CoinComparator implements Comparator
{
   public int compare(Object firstObject, Object secondObject)
   {
      Coin first = (Coin)firstObject;
      Coin second = (Coin)secondObject;
      if ( first.getValue() < second.getValue() )
         return -1;
      if ( first.getValue() == second.getValue() )
         return 0;
      return 1;
   }
}

Sorting an Array of Objects with a Comparator

Coin[] s = . . . ;
Comparator comp = new CoinComparator();
Arrays.sort(coinArray, comp);

Sorting and Searching ArrayLists

Sorting an ArrayList of Objects with a Comparator

ArrayList Coins = new ArrayList();
//add coins
. . . 
Comparator comp = new CoinComparator();
Collections.sort(coins, comp);

File Purse.java

File PurseTest.java