Problem 293. Generalized sorting
Write generalized sort function sortg() that sorts array elements in “ascending” order with given comparison function. A comparison function takes two arguments and return true if the first argument goes before the second in the specific (strick weak) ordering.
The function have to be stable, that is, if A has elements are “equal” (strictly speaking, both comp(a1, a2) and comp(a2, a1) are false), then the ordering of these elements must be preserved. Since MATLAB's sort() function is stable, sort(A) and sortg(A, @lt) will be equivalent.
(Assume that the input argument A will be a vector, not a matrix, and the comparison function comp() will do scalar expansion like MATLAB's lt() ( < ), that is, comparing scalar with vector is possible.)
Example
A = [1, 0, 0 + 1i]; [B, IX] = sortg(A, @(a, b) abs(a) < abs(b));
=> B == [0, 1, 0 + 1i]; IX == [2 1 3]
(1 and 0 + 1i have the same absolute value, but 1 has to appear before 0 + 1i, as the original ordering.)
Solution Stats
Problem Comments
Solution Comments
Show commentsProblem Recent Solvers23
Suggested Problems
-
2503 Solvers
-
Renaming a field in a structure array
1519 Solvers
-
Equidistant numbers containing certain value in an interval
87 Solvers
-
Project Euler: Problem 3, Largest prime factor
1431 Solvers
-
swap sign sum & multiply castles
62 Solvers
More from this Author1
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!