简体   繁体   中英

quicksort matlab, recursive function

I need to write a recursive function embedded with quicksort algorithm. I'm having trouble when updating the new boundaries. y is a matrix and m is the num of the row needs to be sorted.Please help...

function [y]=quicksort(y,left,right,m)

i=left;
j=right;
num=randi(length(y)); % pick a random element in the array as pivot
pivot=y(m,num);

if i <= j %find the element fits criteria below before i overlaps j.
while y(m,i) < pivot
    i = i + 1;
end
while y(m,j) > pivot
    j = j - 1;
end
    ytmp=y(:,j);
    y(:,j)=y(:,i);
    y(:,i)=ytmp;
    i = i + 1;
    j = j - 1;  
%swap the positions of the two elements when y(m,j) < pivot < y(m,i)

else 
return
end

return 
[y]=quicksort(y,i,right,m);  %update the boundaries.
[y]=quicksort(y,left,j,m);   %recursively call the function.

You have done some errors. However, since this seems to be homework I will give you some concrete hints and examples instead of posting the right answer directly. I also limit this to a single vector to keep the answer simpler and more concise.

First, you want to swap all elements which are on the wrong side of the pivot element, not only the first element. So the tip is to use a while loop. You will however still need to do the swapping somewhere, so you will need an if-statement somewhere as well. Secondly, the last return will always be executed. This means that you will never enter the recursion. Try to instead use a condition where you only continue iterating in case the number of elements left exeeds one.

if (i < right)
    y=qsort(y,i,right);  %update the boundaries.
end
if (left < j)
    y=qsort(y,left,j);   %recursively call the function.
end

Hope this information is enough. Good luck!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM