Graph Theory37 sections · 1633 units
Open in Course

Application - Sorting with Swaps

(Minimum swaps to sort)

Given an unsorted array, find the minimum number of swaps to sort it. Think of it as a permutation where p[i] is the value at index ii. You want to reach the identity permutation. Each cycle of length LL requires L1L - 1 swaps to sort. Sum across all cycles. This gives you the minimum number of swaps.

The formula is simple but effective. This is a direct application of cycle decomposition. Find the cycles, count their lengths, and compute the answer as (Li1)\sum (L_i - 1) for all cycles. Every element must return to its correct position.