Discover MakerZone

MATLAB and Simulink resources for Arduino, LEGO, and Raspberry Pi

Learn more

Discover what MATLAB® can do for your career.

Opportunities for recent engineering grads.

Apply Today

Solution 252526

Submitted on 1 Jun 2013 by Yaroslav

Correct

34Size
Leading solution size is 30.
This solution is locked. To view this solution, you need to provide a solution of the same size or smaller.

Test Suite

Test
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));

                    
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));

                    
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));

                    
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));