Search All of the Math Forum:
Views expressed in these public forums are not endorsed by
Drexel University or The Math Forum.


Curious
Posts:
2,140
Registered:
12/6/04


Re: Writing a function with while and for loops
Posted:
Feb 6, 2013 2:41 PM


"Sara" wrote in message <keu6p0$nii$1@newscl01ah.mathworks.com>... > I am asked create a function of 2 inputs, the first defining a vector of random numbers and the second a scalar that sorts the vector in ascending if the scalar is 1 and descending order if the scalar value is 2. If only one input is given the function should sort in ascending order. The function is supposed to use a for loop that is nested in a while loop. The for loop should compare the vector value by value, switching the two as necessary to complete the ascending order. The while loop stops the function once the ascending or descending condition is met. > > So far I don't have much, but here it is. > > > function BubbleSort = ScottS_BubbleSort(x,y) > %UNTITLED3 Summary of this function goes here > % Detailed explanation goes here > > while > for k=x > if k(1) >k(2) %if statement to compare and switch values > > end > end > > end > end
Here is a hint complete with pseudocode (for sorting in ascending order)
<<http://en.wikipedia.org/wiki/Bubblesort>>
In the pseudocode example, replace the "repeat loop" with a "while loop" and you basically have it.
I'll leave the descending part to you.



