Table of Contents

ExplanationImplementation

Official Analysis (C++)

Explanation

For any ii, the value iaii - a_i represents a lower bound on the total number of bubble passes required to sort the array. If iaii - 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(iaii - a_i) is correct, consider any element aia_i where iaii - 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 aia_i. Due to how bubble sort works, aia_i will necessarily move left in every pass until it reaches its correct position, and its iaii - a_i value decreases by 11 with each pass.

Now consider an element aia_i where iaii - a_i equals 00 (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 aia_i to move left instead. Thus, iaii - a_i equals 00 remains unchanged or decreases.

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

Implementation

Time Complexity: O(NlogN)\mathcal{O}(N \log N)

C++

#include <algorithm>
#include <fstream>
#include <iostream>
#include <vector>
using std::cout;
using std::endl;
using std::vector;
struct Entry {

Java

import java.io.*;
import java.util.*;
public class Sort {
Code Snippet: Array Element Class (Click to expand)
public static void main(String[] args) throws Exception {
Kattio io = new Kattio("sort");
int n = io.nextInt();
Entry[] entries = new Entry[n];

Python

from typing import NamedTuple
from functools import cmp_to_key
class Entry(NamedTuple):
val: int
index: int
with open("sort.in") as read:

Join the USACO Forum!

Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!