Explanation
For any , the value represents a lower bound on the total number of bubble passes required to sort the array. If 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() is correct, consider any element where 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 . Due to how bubble sort works, will necessarily move left in every pass until it reaches its correct position, and its value decreases by with each pass.
Now consider an element where equals (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 to move left instead. Thus, equals remains unchanged or decreases.
As a result, max(), if positive, decreases by during each bubble sort iteration. After counting the number of iterations needed to sort the array, we add to account for the final iteration performed by the algorithm, as indicated in the pseudocode.
Implementation
Time Complexity:
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 NamedTuplefrom functools import cmp_to_keyclass Entry(NamedTuple):val: intindex: intwith 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!