Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Out of Sorts Editorial #4997

Merged
merged 2 commits into from
Dec 27, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading