Out of Sorts
Time limit2sMemory limit512 MB
Given an array, count how many times the outer loop of a forward-backward bubble sort variant runs before the array becomes sorted.
- Level
Hard8 of 10
- Topics
- Sorting, Math, Implementation, Greedy
- Solved
- No attempts yet
Problem
Bessie the cow is looking past the farm at longer term career options, so she has started learning algorithms on coding websites.
Her favorite algorithm so far is bubble sort. Here is her first implementation, written in cow-code, for sorting an array of length .
sorted = false
while (not sorted):
sorted = true
moo
for i = 0 to N-2:
if A[i+1] < A[i]:
swap A[i], A[i+1]
sorted = false
In cow-code the moo command does nothing except print moo. Bessie insists on putting it at various points in her code.
After testing her code on several arrays, Bessie noticed something. A large element is pulled to the end of the array very quickly, while a small element can take a long time to bubble up to the front. She suspects that this is where the algorithm gets its name. To reduce the problem, Bessie rewrote the main loop so that each iteration scans forward and then backward. Now a large element and a small element both get a chance to move a long distance in one iteration. Her code looks like this.
sorted = false
while (not sorted):
sorted = true
moo
for i = 0 to N-2:
if A[i+1] < A[i]:
swap A[i], A[i+1]
for i = N-2 downto 0:
if A[i+1] < A[i]:
swap A[i], A[i+1]
for i = 0 to N-2:
if A[i+1] < A[i]:
sorted = false
Given the input array, predict how many times Bessie's rewritten code prints moo.
Input
The first line contains (). Each of the next lines contains one array element, through , an integer with . The elements are not guaranteed to be distinct.
Output
Print how many times moo is printed.