THINK FIRST·CODE LATER

← All labs

Quick sort for many duplicates: three-way partitioning

Problem

With many equal keys, ordinary quick sort wastes time re-sorting them. Write ThreeWayQuick using Dijkstra's three-way partition with pivot a[low] and three indexes lt, i, gt:

  • a[i] < pivot: swap a[lt] and a[i], advance both;
  • a[i] > pivot: swap a[i] and a[gt], decrease gt (do not advance i);
  • equal: advance i.

Afterwards a[lt..gt] equals the pivot and is finished; recurse only on the two outer parts. Count one comparison per loop iteration. Print the array after the first partition with the bounds of the equal block, the sorted array, the comparisons and the recursion depth (the top-level call is depth 1; calls on fewer than two elements do not count).

For the input

9
4 9 4 1 4 7 1 9 4

the program prints

first partition (pivot 4): [1, 1, 4, 4, 4, 4, 9, 7, 9], equal block 2..5
sorted: [1, 1, 4, 4, 4, 4, 7, 9, 9]
comparisons: 11, recursion depth: 2

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

9
4 9 4 1 4 7 1 9 4
What your program must print for d9-6-data-1.txt
first partition (pivot 4): [1, 1, 4, 4, 4, 4, 9, 7, 9], equal block 2..5
sorted: [1, 1, 4, 4, 4, 4, 7, 9, 9]
comparisons: 11, recursion depth: 2

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

Windows PowerShell does not understand <:

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