THINK FIRST·CODE LATER

← All labs

Stable or not? Merge sort versus selection sort

Problem

A sort is stable if elements that compare as equal keep their original relative order. This matters as soon as records are sorted by one field: sorting competitors by score should keep, among equal scores, the order in which they registered.

Write StableMerge with two generic sorts taking a Comparator:

public static <E> void mergeSort(E[] list, Comparator<? super E> order)
public static <E> void selectionSort(E[] list, Comparator<? super E> order)

Read n, then n lines name score. Sort two copies by score, highest first, one with each algorithm; print both results and whether each kept the equal scores in arrival order. For the input

6
Ana 90
Ben 85
Cai 90
Dee 70
Eli 85
Fay 90

the program prints

Merge sort:     [Ana 90, Cai 90, Fay 90, Ben 85, Eli 85, Dee 70]
Selection sort: [Ana 90, Cai 90, Fay 90, Eli 85, Ben 85, Dee 70]
Merge sort kept equal scores in their arrival order: true
Selection sort kept equal scores in their arrival order: false

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-9-data-1.txt

6
Ana 90
Ben 85
Cai 90
Dee 70
Eli 85
Fay 90
What your program must print for d9-9-data-1.txt
Merge sort:     [Ana 90, Cai 90, Fay 90, Ben 85, Eli 85, Dee 70]
Selection sort: [Ana 90, Cai 90, Fay 90, Eli 85, Ben 85, Dee 70]
Merge sort kept equal scores in their arrival order: true
Selection sort kept equal scores in their arrival order: false

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-9-data-1.txt

Windows PowerShell does not understand <:

Get-Content d9-9-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.