Example: Reverse elements in an array - rFronteddu/general_wiki GitHub Wiki

The idea is to use two pointers, one starts at the beginning, the other at the end, and to stop when they meet.

public void reverse(int[] v, int n) {
    int i = 0;
    int j = n-1;
    while(i<j) {
        swap(v, i , j);
        i++;
        j--;
    }
}

void swap(int[] v, int i, int j) {
    int tmp = v[i];
    v[i] = v[j];
    v[j] = tmp;
}