CodeCodeCode

ENGR132: HW05 - vector_sort_name

May 1st, 2012
44
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
MatLab 1.46 KB | None | 0 0
  1. function vec_out = vector_sort_name(vec_in)
  2.  
  3. % FUNCTION: Sorts a given vector numerically.
  4. %
  5. % INPUTS:
  6. % 1) vec_in: The vector given by the user.
  7. %  
  8. % OUTPUTS:
  9. % 1) vec_out: The sorted vector.
  10.  
  11. %Checks whether vec_in is empty or has one value.
  12. if  isempty(vec_in) || (length(vec_in) == 1)
  13.     vec_out = vec_in;
  14. %If vec_in has more than 1 value.
  15. else
  16.     %count_s counter delcared as 1 for second (point) loop to function.
  17.     count_s = 1;
  18.     %Goes through array count_f times to check for unsorted values for final
  19.     %output.
  20.     for count_f = (1:1:length(vec_in) * 2)
  21.         %Goes through array count_s times to check for unsorted values at
  22.         %individual points.  
  23.         for count_s = (1:1:length(vec_in) - count_s)
  24.             %If value 1 is more than value 2 in array, values are flipped
  25.             %using the temp variable as an intermediate.
  26.             if vec_in(count_s) > vec_in(count_s + 1)
  27.                 temp = vec_in(count_s);
  28.                 vec_in(count_s) = vec_in(count_s + 1);
  29.                 vec_in(count_s + 1) = temp;
  30.             end %If (flipper) end
  31.         end %For (point) end
  32.     end %For (total) end
  33.     %Sets sorted vec_in as vec_out for output.
  34.     vec_out = vec_in;
  35. end %If (checking) end
  36.  
  37. % vec_out = vector_sort_name([10 9 8 7 6 5])
  38. %
  39. % vec_out =
  40. %
  41. %      5     6     7     8     9    10
  42. %
  43. % vec_out = vector_sort_name([4 12 3 11 17 9])
  44. %
  45. % vec_out =
  46. %
  47. %      3     4     9    11    12    17
Advertisement
Add Comment
Please, Sign In to add comment