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 195517

Submitted on 23 Jan 2013 by Alfonso Nieto-Castanon

Correct

3Size
This is the leading solution.
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
 
%%
feval(@assignin,'caller','score',250);

                    
2
Pass
 
%% number of comparisons needed
global totalNCompare
totalNCompare = 0;

                    
3
Pass
 
%% simple highest ranking
compareFcn = @(x,y) x(1) > y(1);
y = [6 3 1 9 5];
x_correct = [9 6 5];
profile on
x = partial_sort(y,3,compareFcn);
assert(isequal(x,x_correct))
profile off
stats = profile('info');
found = false;
for i = 1:length(stats.FunctionTable)
    functionName = stats.FunctionTable(i).FunctionName;
    numCalls = stats.FunctionTable(i).NumCalls;
    if ~isempty(strfind(functionName,'@(x,y)x(1)>y(1)'))
        found = true;
        break
    end
end
assert(found)
global totalNCompare
totalNCompare = totalNCompare + numCalls;

                    
4
Pass
 
%% shortest strings
compareFcn = @(x,y) length(x) < length(y);
y = {'a','bc','def','ghij','klmno','pqrstu'};
x_correct = {'a','bc','def','ghij'};
profile on
x = partial_sort(y,4,compareFcn);
assert(isequal(x,x_correct))
profile off
stats = profile('info');
found = false;
for i = 1:length(stats.FunctionTable)
    functionName = stats.FunctionTable(i).FunctionName;
    numCalls = stats.FunctionTable(i).NumCalls;
    if ~isempty(strfind(functionName,'@(x,y)length(x)<length(y)'))
        found = true;
        break
    end
end
assert(found)
global totalNCompare
totalNCompare = totalNCompare + numCalls;

                    
5
Pass
 
%% order by division
compareFcn = @(x,y) mod(x(1),y(1)) == 0;
y = [1 2 3 4 5 6 10 12 15 20 30 60];
x_correct = [60 30 12 20];
profile on
x = partial_sort(y,4,compareFcn);
assert(isequal(sort(x),sort(x_correct)))
profile off
stats = profile('info');
found = false;
for i = 1:length(stats.FunctionTable)
    functionName = stats.FunctionTable(i).FunctionName;
    numCalls = stats.FunctionTable(i).NumCalls;
    if ~isempty(strfind(functionName,'@(x,y)mod(x(1),y(1))==0'))
        found = true;
        break
    end
end
assert(found)
global totalNCompare
totalNCompare = totalNCompare + numCalls;

                    
6
Pass
 
%%
global totalNCompare
feval(@assignin,'caller','score',totalNCompare);