Thursday, January 26, 2012

Reverse an array

Write both iterative and recursive methods for reversing an array

Iterative Method:

void reverseArray(int arr[], int start, int end)
{
  int i;
  int temp;
  while(start < end)
  {
    temp = arr[start];
    arr[start] = arr[end];
    arr[end] = temp;
    start++;
    end--;
  }
}  
Recursive Method
void reverseArray(int arr[], int start, int end)
{
   int temp;
   if(start >= end)
     return;
   temp = arr[start];
   arr[start] = arr[end];
   arr[end] = temp;
   reverseArray(arr, start+1, end-1);
}

No comments:

Post a Comment