Cody

# Problem 293. Generalized sorting

Solution 483873

Submitted on 7 Aug 2014 by rifat
This solution is locked. To view this solution, you need to provide a solution of the same size or smaller.

### Test Suite

Test Status Code Input and Output
1   Pass
%% trivial case [b2, ix2] = sortg([], @lt); assert(isempty(b2) && isempty(ix2));

2   Pass
%% usual less than a = rand(1, 100); [b1, ix1] = sort(a); [b2, ix2] = sortg(a, @lt); assert(isequal(b1, b2) && isequal(ix1, ix2));

c = Columns 1 through 16 70 30 19 44 14 67 12 32 99 64 37 53 54 46 93 38 Columns 17 through 32 75 0 55 73 63 60 81 65 5 97 4 18 77 98 83 26 Columns 33 through 48 56 11 61 42 43 58 25 89 9 59 47 27 90 34 35 85 Columns 49 through 64 28 13 51 45 50 16 76 29 79 40 8 52 1 7 22 72 Columns 65 through 80 62 74 6 66 39 78 57 41 94 68 10 96 69 24 23 3 Columns 81 through 96 92 86 15 31 48 33 88 49 21 2 91 87 84 95 80 17 Columns 97 through 100 36 20 82 71

3   Pass
%% descending order a = rand(1, 100); [b1, ix1] = sort(a, 'descend'); [b2, ix2] = sortg(a, @gt); assert(isequal(b1, b2) && isequal(ix1, ix2));

c = Columns 1 through 16 23 52 68 58 56 74 62 11 88 36 29 80 38 12 20 21 Columns 17 through 32 0 85 22 72 78 44 41 14 63 43 46 6 60 16 19 69 Columns 33 through 48 89 94 17 95 13 66 99 37 54 55 93 34 75 18 71 98 Columns 49 through 64 90 49 26 77 57 3 87 70 79 33 81 67 1 59 42 64 Columns 65 through 80 4 84 25 8 96 15 76 61 32 97 40 65 48 83 7 2 Columns 81 through 96 10 27 35 86 24 47 53 28 51 73 91 31 9 39 50 5 Columns 97 through 100 45 82 30 92

4   Pass
%% small absolute value first a = randn(1, 100) + randn(1, 100)*1i; [~, ix1] = sort(abs(a)); b1 = a(ix1); [b2, ix2] = sortg(a, @(a, b) abs(a) < abs(b)); assert(isequal(b1, b2) && isequal(ix1, ix2));

c = Columns 1 through 16 43 80 69 11 83 52 47 76 79 51 10 62 94 35 3 36 Columns 17 through 32 20 93 9 32 84 71 74 82 78 50 91 53 68 40 59 39 Columns 33 through 48 49 75 98 66 21 15 41 54 31 73 1 72 38 28 55 23 Columns 49 through 64 37 63 58 16 57 19 45 29 61 92 97 27 99 6 65 24 Columns 65 through 80 12 17 90 22 2 95 13 67 46 34 25 18 56 64 30 4 Columns 81 through 96 77 48 8 85 0 96 5 7 14 70 26 60 33 44 89 42 Columns 97 through 100 87 81 86 88

5   Pass
%% stable sort a = randi(10, 1, 100); [b1, ix1] = sort(a); % MATLAB's sort() is stable [b2, ix2] = sortg(a, @lt); assert(isequal(b1, b2) && isequal(ix1, ix2));

c = Columns 1 through 16 88 88 88 17 41 0 8 70 30 60 30 41 70 88 88 54 Columns 17 through 32 17 30 79 8 30 30 88 70 0 79 60 79 8 60 54 30 Columns 33 through 48 41 17 8 17 88 41 30 60 79 70 17 88 79 30 60 70 Columns 49 through 64 60 41 8 17 8 41 17 41 0 0 41 41 17 88 79 0 Columns 65 through 80 41 54 70 17 88 60 30 54 17 54 8 17 30 70 79 70 Columns 81 through 96 79 60 88 8 0 79 41 60 60 54 17 41 0 30 17 70 Columns 97 through 100 88 8 41 0