Skip to content

Commit

Permalink
Merge pull request #4997 from JoltedCowIceCream/patch-1
Browse files Browse the repository at this point in the history
Out of Sorts Editorial
  • Loading branch information
dongliuu authored Dec 27, 2024
2 parents d322bfc + c3fc4d2 commit 85e4b61
Showing 1 changed file with 11 additions and 1 deletion.
12 changes: 11 additions & 1 deletion solutions/silver/usaco-834.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,21 @@
id: usaco-834
source: USACO Silver 2018 US Open
title: Out of Sorts
author: Brad Ma, Kevin Sheng, Juheon Rhee
author: Brad Ma, Kevin Sheng, Juheon Rhee, David Guo
---

[Official Analysis (C++)](http://www.usaco.org/current/data/sol_sort_silver_open18.html)

## Explanation

For any $i$, the value $i - a_i$ represents a lower bound on the total number of bubble passes required to sort the array. If $i - a_i$ is positive, it indicates that the element needs to move left by at least that amount. If it is negative, it is still a valid lower bound since the element does not need to move further left.

To understand why max($i - a_i$) is correct, consider any element $a_i$ where $i - a_i$ is positive (meaning it is to the right of its correct position). For this to happen, there must be some larger element to the left of $a_i$. Due to how bubble sort works, $a_i$ will necessarily move left in every pass until it reaches its correct position, and its $i - a_i$ value decreases by $1$ with each pass.

Now consider an element $a_i$ where $i - a_i$ equals $0$ (the element is already in its correct position). Such an element may or may not move left, but it will not move right. For it to move right, the element immediately to its right would need to be smaller, which implies there is a larger element to its left, causing $a_i$ to move left instead. Thus, $i - a_i$ equals $0$ remains unchanged or decreases.

As a result, max($i - a_i$), if positive, decreases by $1$ during each bubble sort iteration. After counting the number of iterations needed to sort the array, we add $1$ to account for the final iteration performed by the algorithm, as indicated in the pseudocode.

## Implementation

**Time Complexity:** $\mathcal{O}(N \log N)$
Expand Down

0 comments on commit 85e4b61

Please sign in to comment.