Sorting a List of Integers

An algorithm for sorting a list of numbers on paper could be:
  1. Scan through the list looking for the smallest number
  2. Put that number on a second list
  3. Cross the number off of the first list
  4. Repeat the first 3 steps until there are no more numbers left
This requires two lists and "crossing off" numbers is not easy to represent. A better way is to sort the items in place. We put the smallest item in its proper place by swapping it with the item that is already there. The pseudo-code for this could be:
  For count going from 0 through length - 2
    Find minimum value in list[count . . length - 1]
    Swap minimum value with list[count]
Notice that the loop only goes up to length - 2; when count equals length - 1, the last value list[count] will be in the correct position.

Suppose you have two integer variables, x and y. To swap (exchange) their contents, why can't you simply do the following?

x = y;
y = x;
Swapping the contents of two variables requires a temporary variable. You would need to do the swap this way:
int temp;

temp = x;
x = y;
y = temp;
A graphical view of this sort method is here.

Next page

Back to Index
Back to Outline