The red positions form a uniformly chosen subset of size , so there are equally likely colour patterns. A contiguous red block can start at positions , giving exactly favourable patterns. ThereforeIf the cards are regarded as individually labelled, each colour pattern corresponds to permutations, so the same counting argument still applies. In the edge case , the formula correctly gives probability one.
A three-way quicksort can use a common partition helper so that the tree factorisation below makes the same key comparisons. The Every non-pivot entry appears in exactly one partition, and the equal bucket contains the original pivot exactly once. The recursive sublists have length at most one less than the current finite input, so recursion terminates. Induction gives sorted recursive results with the original multiplicities; placing the equal bucket between them gives a sorted permutation of the input. There is no recursive call on the equal bucket, which avoids needless descent on repeated keys.
compare operation is assumed to be a terminating lawful total ordering on the supplied keys.partition3 :: Ord a => a -> [a] -> ([a],[a],[a])
partition3 pivot = foldr step ([],[],[])
where
step x rest =
let (lo,eq,hi) = rest
in case compare x pivot of
LT -> (x:lo,eq,hi)
EQ -> (lo,x:eq,hi)
GT -> (lo,eq,x:hi)
sort :: Ord a => [a] -> [a]
sort [] = []
sort (pivot:xs) =
let (lo,eq,hi) = partition3 pivot xs
in sort lo ++ (pivot:eq) ++ sort hiChoose each row from the permutations of the symbols:Every Latin square remains a candidate, because each of its rows is one of those permutations. Conversely every candidate has valid rows, so only its columns still need checking. There are candidates instead of : at order four, rather than more than four billion. The improvement is substantial but does not make exhaustive generation practical at arbitrary orders. One can replace
squaresRows :: Int -> [[[Int]]]
squaresRows n
| n < 0 = error "negative order"
| otherwise = cp (replicate n (perms [1..n]))
latinRows :: Int -> [[[Int]]]
latinRows = filter valid . squaresRowsvalid by a column-only test here, since row validity is guaranteed by construction.Merge by comparing the present heads and consuming just the chosen one. The implementation uses only the functional representation:The two recursive inputs are the disjoint initial and final portions of the represented sequence; they preserve every occurrence and have smaller lengths when . In
merge' :: Ord a => List a -> List a -> List a
merge' left right
| null' left = right
| null' right = left
| head' left <= head' right =
cons' (head' left) (merge' (tail' left) right)
| otherwise =
cons' (head' right) (merge' left (tail' right))
mergeSort' :: Ord a => List a -> List a
mergeSort' input =
let n = length' input
middle = n `div` 2
in if n <= 1 then input
else merge' (mergeSort' (take' middle input))
(mergeSort' (drop' middle input))merge', the smaller current head can precede every remaining value in both sorted inputs. Selecting the left head on equality preserves stability. Each merge step reduces the total number of remaining elements, and induction proves a sorted permutation of the original sequence.This establishes algorithm termination and correctness on total finite representations, not an unconditional implementation bound. Nested index functions can make queries costly, and repeatedly finding lengths or heads may revisit them. The familiar merge-sort bound assumes suitable constant-time access or consumption primitives; the source's function-only representation supplies no such cost guarantee.
Let and describe the entry state. The postcondition is: the multiset is empty; the returned chain is sorted nondecreasingly; its node sequence is a permutation of . Thus it has exactly the original multiset of data and preserves all duplicates. Strict increase is impossible when the multiset contains repeated values.
def getAllSorted(): Node = {
var head: Node = null
var tail: Node = null
while (bagHeader.next != null) {
val nextSmallest = findMin(bagHeader.next)
delete(nextSmallest)
nextSmallest.next = null
if (head == null) head = nextSmallest
else tail.next = nextSmallest
tail = nextSmallest
}
head
}The loop invariant partitions the original node identities into the remaining multiset and the returned-prefix chain. The latter is sorted, its last node is
tail, and every datum in it is no larger than every remaining datum. Selecting a minimum and appending that detached node preserves all these facts. The loop variant is the number of real nodes remaining in the multiset, decreasing by one. When it reaches zero the string prefix contains the entire original node set, proving the postcondition. An initially empty multiset returns null.This is linked-list selection sort. Its time is in general, from successive scans of lengths , and it uses constant auxiliary space: it relinks original nodes instead of allocating a new node for each item.
The rule of product says that if a construction has stages, with exactly choices at stage after every permitted earlier history, then it has possible outcomes. The later choices need not be identical sets after different histories; their numbers must have the stated values.
For a permutation of distinct objects, choose the first object in ways, the second in ways, and continue until only one remains. Thus the number isEvery ordered arrangement is produced exactly once by its successive choices, so this counts permutations without omissions or repetitions. For , the unique empty arrangement agrees with .
For the defined shuffle, Here the identity's period means the least positive number of applications, so the empty and two-element lists have period one. Since is odd, is invertible modulo , ensuring termination. Using
count 52 = 8. The printed assertion about seven shuffles is inconsistent with the actual permutation. Number positions from zero. On an even length , a position moves to , while the last position stays fixed. Indeed, positions in the first half move to , and positions in the second half move to . Consequently the number sought is the multiplicative order of modulo :count :: Int -> Int
count n
| n < 0 || odd n = error "count: nonnegative even length required"
| n <= 2 = 1
| otherwise = go 1 (2 `mod` m)
where
m = toInteger n - 1
go k r
| r == 1 = k
| otherwise = go (k+1) ((2*r) `mod` m)Integer for residues avoids overflow in doubling; the mathematical correctness assumes the returned period fits Int. The algorithm uses one modular update per shuffle in the period, rather than constructing each shuffled deck.For , , whereas , and are not congruent to one, ruling out every proper divisor of eight. After seven shuffles, the original position is at position , not back at .
An eight-step position cycle under the 52-card perfect out-shuffle
. Details. This single position already disproves a seven-step return; the modular calculation proves that the whole permutation returns after eight.
Sort the two halves ascending, reverse the second, and concatenate to form a bitonic sequence:For a power-of-two length greater than one, both halves are smaller powers of two. By induction, the recursive calls return ascending permutations of their respective inputs. Reversal makes the second half descending, so part (e)'s precondition holds and
sort :: Ord a => [a] -> [a]
sort [] = []
sort [x] = [x]
sort xs = merge (sort as ++ reverse (sort bs))
where (as,bs) = halve xsmerge sorts their concatenation without losing entries. This proves both sortedness and sorting permutation preservation. Its recurrence relation is , so summing the levels gives time. Equal keys cause no difficulty; ascending and descending here permit equality. This is a bitonic sorting algorithm. Perfect elimination ordering 2026-10-14
A perfect elimination ordering of a finite simple graph is a permutation of its vertices such that each set of later graph neighboursis a clique. Thus is a simplicial vertex in the remaining induced subgraph . Empty and one-vertex sets satisfy the clique condition automatically. The order here is the order of deletion: goes first.
The characterization is powerful: a finite simple graph is a chordal graph if and only if it has a perfect elimination ordering. For one proof outline, the earliest vertex of an induced cycle of length at least four would have two later graph neighbours on that graph cycle that are not adjacent, contradicting the clique condition. Conversely, every nonempty chordal graph has a simplicial vertex, and every induced subgraph of a chordal graph is a chordal graph; repeatedly deleting such a vertex supplies the ordering.[ref]
In the square-plus-diagonal chordal graph above, is a perfect elimination ordering, with later graph neighbourhoods , , , and . Starting instead with fails: its graph neighbours do not form a clique, because is absent. Thus even a chordal graph can have a poor elimination ordering.
For a larger example, join three triangles along shared edges, usingThe exact graph neighbourhoods are , , , , and . The ordering has later graph neighbourhoods , , , , and , all cliques; this certifies that the graph is a chordal graph without enumerating its graph cycles. Its maximal cliques , , form a junction tree in that order, with intersections and .
A perfect elimination ordering removes three overlapping triangles without fill-in; choosing the central vertex first adds three edges
. Details. To find an ordering, maximum cardinality search starts with all scores zero, repeatedly selects an unselected vertex of largest score, and increases each unselected graph neighbour's score by one. Reverse the selection order to obtain a candidate perfect elimination ordering. For the three-triangle graph, one valid selection sequence is , with scores at selection ; reversing it gives the displayed deletion order. On a chordal graph every tie choice works. On an arbitrary graph, test the resulting later graph neighbourhoods for the clique condition to recognize chordal graphs. Suitable adjacency lists, score buckets and a linear-time verification method give recognition.[ref]
The deletion rule also explains sparse Gaussian elimination. For a symmetric positive-definite matrix whose matrix graph is , eliminating pivot applies the Schur complement updateOnly pairs of remaining graph neighbours of can acquire new off-diagonal entries. A perfect elimination ordering already has all those edges, so Cholesky decomposition creates no symbolic fill-in. Positive definiteness ensures nonzero pivots in exact arithmetic. Special numerical cancellation can suppress predicted entries, and floating-point rounding affects their values.[ref]
Chordal Graphs and Semidefinite Optimization by Lieven Vandenberghe and others. §9.1; equation 9.2; Theorem 9.1
In the three-triangle graph, deleting first instead connects every pair in and adds exactly . The graph was already a chordal graph; the extra fill-in comes from the ordering.One further reward is optimal graph coloring. Process a perfect elimination ordering backwards and give each vertex the smallest positive color absent from its already colored graph neighbours. Those graph neighbours form a clique, so this greedy algorithm uses at most the clique number colors; any clique of that size requires at least that many. In the three-triangle graph, coloring gives colors , so both the chromatic number and the clique number are three. Every maximal clique also occurs among : take its earliest vertex and use maximality. The same ordering therefore supports graph coloring, maximal clique extraction and sparse computation.
Historically, Donald J. Rose, Robert E. Tarjan and George S. Lueker's 1976 paper connected graph elimination to symmetric sparse matrices and gave a search-based algorithm for finding a perfect elimination ordering when one exists. Its abstract distinguishes a minimal elimination ordering from a minimum one: removing avoidable fill-in does not by itself minimize the total number of added edges.[ref]
Perfect out-shuffle 2026-10-24
Interleave the two equal halves of an even finite list, placing the first half's next entry before the second half's next entry. With zero-based positions and length , position moves to , and the last position stays fixed. For an index in the first half the new position is ; in the second it is , proving the formula. The least positive period of the whole permutation is the multiplicative order of modulo : equality of the multiplier to one fixes every position, and fixing position one requires that equality. In particular, a 52-entry list has period eight. The empty and two-entry cases are identity permutations with least positive period one.
Permanent as probability of distinct independent choices Created 2026-10-14 Updated 2026-10-20
Let be independent random variables, each choosing a label from . Put their probabilities in the matrix , where . Each row sums to one. All choices are distinct precisely when their ordered list is one of the permutations of the labels. These are mutually exclusive events, and independence makes the probability of one list equal to . Adding the list probabilities gives the permanent of a matrix:In particular, this permanent lies between zero and one.
For a two-person example,The distinct outcomes and have probabilities and . ThereforeThe colliding outcomes and have probabilities and , totaling . All four outcomes are shown below; their probabilities sum to one.
The permanent adds the probabilities of distinct choices: two successful outcomes have total probability 0.65
. Details. If every choice has the uniform distribution on a finite set of labels, then and the distinct-choice probability is . For three choices and three labels it is . This counts a subset of all ordered outcomes, not independent pairwise collision events. Independence of the original choices is essential: without it, the individual rows of do not determine the joint probabilities.
Permanent (mathematics) Created 2026-10-14 Updated 2026-10-20
The permanent of a matrix adds the products obtained by choosing one entry in each row and one in each column. For an matrix with entries in the real numbers or complex numbers,Here each permutation chooses column in row , and the symmetric group lists every such bijection. The formula resembles the Leibniz formula for determinants, but omits the sign of a permutation. For a two-by-two matrix,The absence of alternating signs makes the permanent of a matrix particularly useful for counting allowed assignments.
For a zero-one matrix, let rows represent people, columns represent jobs, and mean that person can do job . This is the biadjacency matrix of a bipartite graph. A product in the permanent is one exactly when all the selected assignments are allowed; otherwise it is zero. Each surviving permutation assigns every person a different job, which is a perfect matching. Thus the permanent counts perfect matchings. This interpretation and the definition are given in Yufei Zhao, Probabilistic Methods in Combinatorics, §10.2, pp. 178–179.
For a fully enumerated example, takeAmong the six permutations of three columns, exactly three give nonzero products: , and . These tuples list the chosen column in each successive row. Each product is one, so . Their permutation signs are , giving . The diagram displays all three allowed assignments.
Three allowed one-to-one assignments contribute positively to the permanent, while their permutation signs give a determinant of minus one
. Details. A zero determinant need not mean that no assignment exists. The two-by-two all-ones matrix has permanent and determinant : its two assignments cancel in the determinant. The nonzero determinant criterion for a perfect matching is sufficient for existence, but the converse fails for a fixed zero-one matrix.
For nonnegative entries, the permanent instead sums assignment weights, with each assignment weighted by the product of its selected entries. It is then a total weight rather than necessarily an integer count. With arbitrary entries in the real numbers or complex numbers, even the permanent can have cancellation; the counting interpretation specifically uses zero-one entries. The permanent as probability of distinct independent choices gives another useful nonnegative interpretation.
There are terms in the defining sum, linking direct evaluation to the factorial. For the all-ones matrix, every term is one and the permanent is exactly ; the identity matrix has permanent one. Finding one allowed assignment and counting all allowed assignments are different questions. Their relationship to computational complexity theory was studied in L. G. Valiant, The complexity of computing the permanent, Theoretical Computer Science 8(2), 189–201, 1979. The elementary sum is useful for small examples, while the existing dense permanent approximation describes a more specialized way of estimating large counts.
Permutation Created 2026-09-24 Updated 2026-10-13
A permutation of a set is a bijection : every element has exactly one image and every element appears exactly once as an image. For a finite set, a permutation can also be recorded as an ordering of all its elements, once a reference order has been chosen. For three distinct letters , the six orderings areThere are three choices for the first letter, two unused letters for the second, and one for the third. Every path in the tree gives one complete ordering, and every ordering has one such path, so the rule of product gives , a factorial.
The full choice tree for the six permutations of three distinct letters: three first choices, two second choices, and one third choice
. Details. Ordering versus mapping. Label the reference positions . An ordering tuple of these labels describes the function ; conversely, reading the images recovers the ordering. For example,means , , , . Its ordered image list is , whereas its cycle decomposition of a permutation is : starting at , follow its successive images back to . Parentheses in the latter expression encode arrows around a permutation cycle, rather than an image list in reference order. [ref]
https://math.mit.edu/~fgotti/docs/Courses/C.%20Combinatorial%20Analysis/11.%20Permutations%20I/Permutations%20I.pdf. Felix Gotti, MIT 18.211, lecture 11, pages 1–2: arrangements, bijections and cycles
The two viewpoints answer different useful questions about the same object. An ordering tells us which object occupies each position; a bijection tells us where each label is sent and allows successive rearrangements through function composition. All permutations of labels form the symmetric group, whose subgroups are permutation groups. The counting viewpoint supplies possibilities, a factorial; the mapping viewpoint reveals how rearrangements combine.
Composition convention. Apply the rightmost permutation first:For the displayed and the transposition , direct evaluation givesFor instance, , but . Thus function composition of permutations need not be commutative; the omitted labels in these permutation cycles are fixed points.
Permutation cube identity criterion 2026-10-31
For a bijection , composing with gives , and composing the latter with gives the converse. Every orbit therefore has size one or three: the permutation consists of fixed points and disjoint three-cycles. This applies to an infinite underlying set as well as a finite one, since each individual orbit has at most three elements.
Permutation diagram 2026-10-20
A diagram of straight segments joining two parallel lines, with distinct endpoints on each line. Ordering the endpoints along the two lines encodes a permutation; crossing segments define the associated permutation graph.
Permutation generation by insertion 2026-10-31
Generate every permutation of a finite list by recursively permuting its tail and inserting its head into each possible position. For distinct input elements, every shorter permutation has insertion positions, giving results. Removing the distinguished head reconstructs the unique shorter permutation and insertion position.
Permutation graph 2026-10-20
The intersection graph of the segments in a permutation diagram. Two segments cross exactly when their endpoint orders disagree. A set of mutually noncrossing segments corresponds to a monotone subsequence of the endpoint permutation.
Permutation group 2026-10-14
A subgroup of the symmetric group of a set, acting faithfully by permutations. A finite permutation group specified by generators can be enumerated by repeatedly multiplying the elements already found by those generators until no new element appears. Its orbits and conjugacy classes can then be computed directly.
Conjugation preserves order of a group element, because , and preserves the sign of a permutation, because sign is a group homomorphism into . These invariants do not determine cycle type. In , and both have order three and positive sign, but have three and zero fixed points respectively. Conjugation relabels cycles, so these permutations are not conjugate.
Permutation-preimage quantum search 2026-10-06
To find an input of a permutation whose output lies in a known -element subset, compute the output, apply its marked-state phase oracle, and use uncomputation. A modular-addition quantum oracle costs two forward queries per marked reflection, because modular-oracle inversion by negation supplies its inverse. Amplitude amplification then uses queries for fixed success probability. Positive-square outputs have and hence query cost .




