THINK FIRST·CODE LATER

← All labs

Tracing quick sort with the Lomuto partition

Problem

Implement quick sort with the Lomuto partition (pivot = last element of the range, elements <= pivot go left) and print the whole array after every partition.

Input: an integer n (n ≥ 0), followed by n integers.

Algorithm: quickSort(lo, hi) does nothing if lo >= hi. Otherwise it partitions a[lo..hi], obtaining the pivot's final index p, prints one line, then sorts lo..p-1 and then p+1..hi.

Output: after each partition, the line

pivot <value> at <p>: <whole array, printed with Arrays.toString>

and at the end two lines, Sorted: … and Partitions: <number of partitions>. For 7 / 7 2 9 4 3 8 5:

pivot 5 at 3: [2, 4, 3, 5, 9, 8, 7]
pivot 3 at 1: [2, 3, 4, 5, 9, 8, 7]
pivot 7 at 4: [2, 3, 4, 5, 7, 8, 9]
pivot 9 at 6: [2, 3, 4, 5, 7, 8, 9]
Sorted: [2, 3, 4, 5, 7, 8, 9]
Partitions: 4

Try a sorted input and an input of equal values: the trace shows the worst case.

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

7
7 2 9 4 3 8 5
What your program must print for d9-2-data-1.txt
pivot 5 at 3: [2, 4, 3, 5, 9, 8, 7]
pivot 3 at 1: [2, 3, 4, 5, 9, 8, 7]
pivot 7 at 4: [2, 3, 4, 5, 7, 8, 9]
pivot 9 at 6: [2, 3, 4, 5, 7, 8, 9]
Sorted: [2, 3, 4, 5, 7, 8, 9]
Partitions: 4

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

Windows PowerShell does not understand <:

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