THINK FIRST·CODE LATER

← All labs

A generic bubble sort, with and without a Comparator

Problem

Write BubbleGeneric with two versions of the same sort:

public static <E extends Comparable<E>> void bubbleSort(E[] list)
public static <E> void bubbleSort(E[] list, Comparator<? super E> order)

The first must simply call the second with Comparator.naturalOrder(). The sort stops as soon as a whole pass makes no swap; count the passes and the swaps.

main reads a line of words and prints: the words in natural order; the words by length, then alphabetically; what happens when the already sorted array is sorted again; and the lengths of the words, largest first (an Integer[] sorted with Comparator.reverseOrder()). For the input

pear fig banana kiwi apple date

the program prints

Natural order: [apple, banana, date, fig, kiwi, pear] (5 passes, 11 swaps)
By length, then alphabet: [fig, date, kiwi, pear, apple, banana] (5 passes, 8 swaps)
Sorting the sorted array again: 1 pass, 0 swaps
Word lengths, largest first: [6, 5, 4, 4, 4, 3]

Data for this lab

Your program reads its data from standard input. Download the file, then give it to your program as shown below. Start with data set 1: its expected output is given.

d9-7-data-1.txt

pear fig banana kiwi apple date
What your program must print for d9-7-data-1.txt
Natural order: [apple, banana, date, fig, kiwi, pear] (5 passes, 11 swaps)
By length, then alphabet: [fig, date, kiwi, pear, apple, banana] (5 passes, 8 swaps)
Sorting the sorted array again: 1 pass, 0 swaps
Word lengths, largest first: [6, 5, 4, 4, 4, 3]

Run your program first, then open this and compare line by line: your output must contain these lines exactly.

How to give the file to my program

Terminal (macOS, Linux, or Windows Command Prompt), after compiling:

java Main < d9-7-data-1.txt

Windows PowerShell does not understand <:

Get-Content d9-7-data-1.txt | java Main

IntelliJ IDEA: Run → Edit Configurations → Redirect input from. Or simply paste the content of the file into the console when the program waits for input.

Write it here or in your IDE, then paste it. Compile and test it yourself before comparing. Your code stays in your browser — it is never sent to or stored on the server.