C++ Notes: Example - reverse

Reverses the elements in an array of n elements. When it is finished, the element at a[0] will be exchanged with a[n-1], a[1] exchanged with a[n-2], etc.

void reverse(int a[], int n) {
    // function: Reverses the elements of a.
    // parameters:
    //    a    inout  array of values.
    //    n    in     number of values in a, a[0]..a[n-1]
    // returns: nothing
   
    for (int i=0; i<n/2; i++) {
        int temp = a[i];
        a[i]     = a[n-i-1];
        a[n-i-1] = temp;
    }
    return;
}

Different use of indexes

void reverse(int a[], int n) {
    int head = 0;   // index of first element
    int tail = n-1; // index of last element
    while (head < tail) {      
        int temp = a[head];
        a[head]  = a[tail];
        a[tail]  = temp;
        head++;
        tail--;
    }
    return;
}

Same algorithm using pointers

void reverse(int* a, int n) {
    int* head = a;     // pointer to first element
    int* tail = a+n-1; // pointer to last element
    while (head < tail) {      
        int temp = *head;
        *head  = *tail;
        *tail  = temp;
        head++;
        tail--;
    }
    return;
}