Bubble Sort
Time limit1sMemory limit128 MB
Swap exactly one pair of elements in the array, then find the minimum number of swaps the given bubble sort performs on the result.
- Level
Hard8 of 10
- Topics
- Sorting, Prefix sum, Greedy
- Solved
- No attempts yet
Problem
Bubble sort is one of the simplest sorting algorithms, described by the pseudocode below. Whenever two adjacent elements are out of order and get swapped, the swap counter increases by one.
void bubble_sort(int *a, int n) {
int i, j;
for (i = 0; i < n - 1; ++i) {
for (j = 0; j < n - 1; ++j) {
if (a[j] > a[j + 1]) {
/* The pair is out of order, so swap the two elements. */
/* This increases the swap count by one. */
int x = a[j];
a[j] = a[j + 1];
a[j + 1] = x;
}
}
}
}
Given an array of length , define an array as follows. Choose two indices and with , and swap the -th and -th elements of exactly once; the resulting array is .
Among all possible arrays , output the smallest number of swaps that the bubble sort above would perform.
Input
The first line contains an integer . Each of the next lines contains one element of the array , given in the order (one per line).
Output
Print the minimum bubble-sort swap count over all arrays .