bubble sort function that sort element of a vector from tha largest to the smallest
Show older comments
defined function that sorts the elements of a vector (of any length) from largest to smallest.
this is my work
function [ y ] = downsort_function( x )
%UNTITLED Summary of this function goes here
% Detailed explanation goes here
n=numel(x);
t=1;
a=0;
while t==1;
for i=1:(n-1)
if x(i)>x(i+1)
x(i+1)=x(i);
t=1;
end
end
end
the problem is when i try to read with my vector, my machine gets stuck. it not giving me anything or i have to restart the machine.
thanks for yr help
Answers (2)
Walter Roberson
on 9 Dec 2012
2 votes
You never set t to 0 so your loop never exits.
4 Comments
James Tursa
on 9 Dec 2012
Also he doesn't swap x(i+1) and x(i), he just sets x(i+1). So even if he fixes the t=0 issue the code will not work.
Walter Roberson
on 9 Dec 2012
Correct, but I was going to let him discover that once the code did not infinite loop.
kevin piaget
on 9 Dec 2012
Edited: Walter Roberson
on 10 Dec 2012
Walter Roberson
on 10 Dec 2012
I cannot seem to locate any Mathworks function named "swap" ?
JayaSaiRamPavan Tanneru
on 22 Feb 2020
x=input('enter:');
k=length(x);
for n=1:k
for m=1:k
if x(n)>x(m)
temp=x(n);
x(n)=x(m);
x(m)=temp;
end
end
end
disp(x);
1 Comment
James Tursa
on 24 Feb 2020
Your m indexing could be better, and you have no short-circuit exit if there are no swaps.
Categories
Find more on Matrix Indexing in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!