Search Program on this blog

Friday 6 November 2015

Write a function called sort3 that takes three scalar arguments. It uses if-statements, possibly nested, to return the three values of these arguments in a single row-vector in increasing order (or more precisely, non-decreasing order), i.e., element one of the output vector equals the smallest input argument and element three of the output vector equals the largest input argument. NOTE: Your function may not use any built-in functions, e.g., sort.

function row = sort3(a,b,c)
if a>=b && a>=c
    if b>=c
        row = [c b a];
    elseif b<=c
        row = [b c a];
    end
elseif b>=a && b>=c
    if a>=c
        row = [c a b];
    elseif a<=c
        row = [a c b];
    end
elseif c>=a && c>=b
    if a>=b
        row = [b a c];
    elseif a<=b
        row = [a b c];
    end
end

3 comments:

  1. How to solve this case then.

    Write a function called sort3 that takes a 3-element vector as its sole arguments. It uses if-statements,
    possibly nested, to return the three elements of the vector as three scalar output arguments in nondecreasing
    order, i.e., the first output argument equals the smallest element of the input vector and the last
    output argument equals the largest element. NOTE: Your function may not use any built-in functions, e.g.,
    sort, min, max, median, etc.

    ReplyDelete
  2. function [s,m,l] = sort3(v)
    if ~isempty(v) == true

    if v(1)>=v(2) && v(1)>=v(3)
    if v(2)>=v(3)
    s=v(3);
    m=v(2);
    l=v(1);
    elseif v(2)<= v(3)
    s=v(2);
    m=v(3);
    l=v(1);
    end
    elseif v(2)>=v(1) && v(2)>=v(3)
    if v(1)>=v(3)
    s=v(3);
    m=v(1);
    l=v(2);
    elseif v(1)<=v(3)
    s=v(1);
    m=v(3);
    l=v(2);
    end
    elseif v(3)>=v(1) && v(3)>=v(2)
    if v(1)>=v(2)
    s=v(2);
    m=v(1);
    l=v(3);
    elseif v(1)<=v(2)
    s=v(1);
    m=v(2);
    l=v(3);
    end
    end
    else
    fprintf ('v a vector 3 ele.\n')
    return
    end
    end

    ReplyDelete
  3. Thank you, I spent whole days on this problem, wrote up to but my mistake was missing last lines

    "........
    else
    fprintf ('v a vector 3 ele.\n')
    return
    end
    end

    ReplyDelete