Check if values are sorted without using predifined issorted function
Show older comments
Hello all, my name is Felipe, and I'm not very experienced in programming, but for a work that I want to apply, I'm being asked for the following tasks, so if anybody could help that would be great!
- Define a vector: [5 4 8 1 5 4 7 4]
- Check if values are sorted (Do not use any predifined sort function)
- In case that the numbers are not sorted, sort them by increasing order.
- After sorting, check if there are any duplicates and remove them, leaving a single value for that number.
- Let the user know the size of the list and if the list has more than 5 items (i.e. “List contains more than 5 items; total items: X”)So I already have made a function but it is not quite polished yet, so I leave it here:
function [sx1] = unt(x)
sx=length(x);
x2=x;
for y = 1:length(x)
[sx(y),ix] = min(x); % crea vector sx de y elementos con el mínimo y su posición ix
x(ix) = []; % borra el mínimo
end
if isequal(sx,x2)
disp('\nIt is sorted')
else
fprintf('\nIt is not sorted - The sorted value is:'); disp(sx);
end
sx1=unique(sx);
fprintf('The value without duplicates is:'); disp(sx1);
i=length(sx1);
if i>5
fprintf('List contains more than 5 items; total items: %d\n',i);
else
fprintf('List contains equal or less than 5 items; total items: %d\n',i);
end
end
First I define the vector x in the command line, then execute the function like this:
x=[5 4 8 1 5 4 7 4];
unt(x)
So I leave this here, in case anyone can help Thanks in advance, Regards
Answers (1)
Walter Roberson
on 22 Feb 2017
0 votes
For values sorted in ascending order, and none of the values are inf or nan, then diff() of the vector is never negative.
Categories
Find more on Shifting and Sorting Matrices in Help Center and File Exchange
Products
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!