THINK FIRST·CODE LATER

← All labs

Counting sort and stability

Problem

Write CountingSortDemo. Read n k, then n records name key with keys in 0 … k. Sort the records by key with counting sort:

  1. count each key (print the counts);
  2. turn the counts into prefix sums (print them);
  3. place the records, scanning the input from right to left.

Records with equal keys must stay in their input order (stable).

For the input

7 3
Ana 2 Bo 0 Cy 3 Di 2 Ed 0 Flo 1 Gus 2

the program prints

counts:    [2, 1, 3, 1]
positions: [2, 3, 6, 7]
sorted: Bo:0 Ed:0 Flo:1 Ana:2 Di:2 Gus:2 Cy:3
Steps: about n + k = 11, no comparisons between keys

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

7 3
Ana 2 Bo 0 Cy 3 Di 2 Ed 0 Flo 1 Gus 2
What your program must print for d9-4-data-1.txt
counts:    [2, 1, 3, 1]
positions: [2, 3, 6, 7]
sorted: Bo:0 Ed:0 Flo:1 Ana:2 Di:2 Gus:2 Cy:3
Steps: about n + k = 11, no comparisons between keys

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

Windows PowerShell does not understand <:

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