Skip to content

Example: Reverse elements in an array

Roberto Fronteddu edited this page Mar 17, 2024 · 1 revision

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;
}
Clone this wiki locally