Math 171 - Alexiades
Lab 4
Sorting

Learn syntax of Matlab functions, for loops, if statements.
(always read the entire Lab before you start doing it. Work in a new folder "Lab4")

A. Sorting numbers: Sorting a list of numbers means to rearrange them from smallest to largest (or reversely).
  1. Swapping: In a basic "bubble-sort", this is done by swapping any that are out of order.
    To swap two values x and y, we need to save one to a temporary variable before overwriting it, like:
 	tmp = x;	%% hold original value of x
	  x = y;	%% store y into x (this overwriting x)
	  y = tmp;	%% now put the saved x into y
    (because doing   x=y; y=x;   would result in both = the original y, and the x value would be lost)
  2. Bubble-sort: To sort an array x of N numbers from small to large, need to check if x(i) > x(i+1), and if so,
    to swap them. Here is one way of doing it:
	for j = 1 : N−1
	    for i = 1 : N−j
		if  x(i) > x(i+1)
		   %% do the swapping here
		end
	    end
	end
Matlab has a sophisticated built-in 'sort' function for sorting: >> help sort   to learn about it.
So we should not use the name "sort" for our functions, and will NOT use it here.
Note: There are many types of sorting algorithms, in addition to "bubble sort", including:
      insertion, merge, quick, heap, radix, counting, binary sort.

B. To do : To sort an array, create two functions, named "sorting" and "Sorter" :
  1. Write a main function sorting in a file sorting.m , which:
  a. Gets an integer N (in argument), generates an array x of N random integers in [1, 100], and prints it out.
  b. Calls the Sorter function to do the sorting of the array x.
  c. Prints the list of sorted numbers.

  2. Write a Sorter function (in separate file Sorter.m) which:
  a. Accepts an array of numbers as input (in argument).
  b. Sorts the array from smallest to largest using bubble-sort as above.
  c. Returns the sorted array.

Debug for N = 5, then test for N=10 and N=50. Document your codes (insert brief comments).

C. Prepare the file Lab4.txt  for submission: Once you have your program working as you want, and well commented:
  1. Turn on diary:   >> diary Lab4.txt
  2. Insert a listing of your codes in the diary:   >> type sorting.m , separator line, and >> type Sorter.m , separator line.
  3. Run your   >> sorting   program for N=10
  4. Close the diary:   >> diary off
  6. Using a PLAIN TEXT editor, edit the file Lab4.txt to clean it up,
   leaving only the correct version of
what is asked for above.
   Make sure your name, lab4, date are at the top.

D. Submit it on Canvas before the due date.