CS 221 Lab 7 Fall 2011: sorting with nested for-loops (Bubble Sort)

Out: 19 October 2011
Due: 27 October 2011

Note Well: The purpose of lab exercises is for you to learn how to solve problems using these tools. It is not for you to type something into MATLAB. As you go through the steps of each exercise, think about what you are doing and what the program is doing, and try to predict what you will see. If you don't understand something, ask your instructor -- that's what he's there for.


Sorting a vector of numbers

In this exercise you will write a MATLAB program that accepts a vector and returns the contents of the vector sorted from smallest element to largest.

Suppose A is the row vector:

A = [38 1 18 5 42 13 0 -9 7 2 -4 6];

Your implementation should produce the below output:

-9 -4 0 1 2 5 6 7 13 18 38 42

Follow these steps to create your script file:

  1. Select "File" -> "New" -> "Script" from the main menu. The editor window should open.

  2. Type "% lab7part1 - sorting a vector using nested for-loops" on the first line in the editor window.

  3. On the next line, create a vector A and put some values in it. You can use the values in the example above or create your own.

  4. On the next line, calculate the length of the vector using the length () function.

  5. Now you need to sort the list by making successive "passes" over the array. On each pass, the largest element will move to the top of the array. In the example above, at the end of the first pass 42 is in the rightmost position, i.e. A(length(A)).

    So you will need to do as many passes as there are elements in the list. (Hint: you just need one for-loop to do all the passes.)

  6. On each pass, start by comparing the first element to the second. If the first is greater than the second, swap them; if not, do nothing. Then compare the second and third elements. Again, if the second element is greater than the third, swap. Continue until you have tested the second-last element against the last element, swapping at each step. (Hint: You need another loop inside the first loop — i.e., a nested loop — to go through the vector in each pass; use an if statement to compare the values.)

    Note: In MATLAB, to swap the values of two variables 'x' 'y' need a third, temporary variable 'temp', so you can do this:

    temp = x;
    x = y;
    y = temp;

    (Except in your code, x and y will be indexed references to elements of the vector you are sorting — that is, A (i), A (i+1), etc.)

  7. When the loops complete, display the contents of the vector.

  8. Save your script as "lab7.m" to the Desktop or your removable media.

  9. Show your script to the instructor.

  10. After the instructor has OK'd your work, upload your script via the submission portal as "Lab 7".

Note: this sorting algorithm is called "bubble sort" because on each pass the largest element "bubbles up" to the top of the array.