Thursday, July 17, 2008

Reversing an array

Let A[1...n] be an array of n distinct numbers. Write a simple linear time algorithm to reverse the order in which the numbers appear on A[1...n]. Use as little additional space as possible. (For example, do not copy the array.)


void reverse(int a[], int n)
{
int i, t;
for(i=0; i < n/2; i++) {
t = a[0];
a[0] = a[n-i-1];
a[n-i-1] = t;
}
}

No comments:

Post a Comment