    01: #include <iostream>
    02: #include <vector>
    03: #include <cstdlib>
    04: #include <ctime>
    05:
    06: using namespace std;
    07:
    08: /**
    09:    Swaps two integers.
    10:    @param x the first integer to swap
    11:    @param y the second integer to swap
    12: */
    13: void swap(int& x, int& y)
    14: {
    15:    int temp = x;
    16:    x = y;
    17:    y = temp;
    18: }
    19:
    20: /**
    21:     Gets the position of the smallest element in a vector range.
    22:     @param a the vector
    23:     @param from the beginning of the range
    24:     @param to the beginning of the range
    25:     @return the position of the smallest element in
    26:     the range a[from]...a[to]
    27: */
    28: int min_position(vector<int>& a, int from, int to)
    29: {
    30:    int min_pos = from;
    31:    int i;
    32:    for (i = from + 1; i <= to; i++)
    33:       if (a[i] < a[min_pos]) min_pos = i;
    34:    return min_pos;
    35: }
    36:
    37: /**
    38:    Sorts a vector using the selection sort algorithm
    39:    @param a the vector to sort
    40: */
    41: void selection_sort(vector<int>& a)
    42: {
    43:    int next; /* the next position to be set to the minimum */
    44:
    45:    for (next = 0; next < a.size() - 1; next++)
    46:    {
    47:       /* find the position of the minimum */
    48:       int min_pos = min_position(a, next, a.size() - 1);
    49:       if (min_pos != next)
    50:          swap(a[min_pos], a[next]);
    51:    }
    52: }
    53:
    54: /**
    55:    Prints all elements in a vector
    56:    @param a the vector to print
    57: */
    58: void print(vector<int> a)
    59: {
    60:    for (int i = 0; i < a.size(); i++)
    61:       cout << a[i] << " ";
    62:    cout << "\n";
    63: }
    64:
    65: /**
    66:    Sets the seed of the random number generator.
    67: */
    68: void rand_seed()
    69: {
    70:    int seed = static_cast<int>(time(0));
    71:    srand(seed);
    72: }
    73:
    74: /**
    75:    Computes a random integer in a range.
    76:    @param a the bottom of the range
    77:    @param b the top of the range
    78:    @return a random integer x, a <= x and x <= b
    79: */
    80: int rand_int(int a, int b)
    81: {
    82:    return a + rand() % (b - a + 1);
    83: }
    84:
    85: int main()
    86: {
    87:    rand_seed();
    88:    vector<int> v(20);
    89:    for (int i = 0; i < v.size(); i++)
    90:       v[i] = rand_int(1, 100);
    91:    print(v);
    92:    selection_sort(v);
    93:    print(v);
    94:    return 0;
    95: }