Intel Interview Question Software Engineer / Developers
0of 0 votesReverse an array without using iteration.
Hint: Recursion.
Team: Firmware
Country: United States
Interview Type: In-Person
Corrected code:-
void reverse(int *a, int n) {
if (n <= 0) return;
swap(a[0], a[n-1]);
reverse(++a, n-2);
}
I guess the check needs to be modified like this
void reverse(int *a, int n) {
if (n <= 1) return;
swap(a[0], a[n-1]);
reverse(++a, n-1);
}
/* Move first element to last position, and shift other elements to left */
void Bubble(T *a, int len){
if (len <= 1) return;
T tmp = a[0];
a[0] = a[1];
a[1] = tmp;
Bubble(++a, --len);
}
void Reverse(T * a, int len) {
Bubble(a, len); /* first move first element to last */
Reverse(a, --len); /* now reverse the initial portition of bubbled array*/
}
Of course, the Reverse needs to to return when length is 1.
So corrected code:
/* Move first element to last position, and shift other elements to left */
void Bubble(T *a, int len){
if (len <= 1) return;
T tmp = a[0];
a[0] = a[1];
a[1] = tmp;
Bubble(++a, --len);
}
void Reverse(T * a, int len) {
if (len <= 1) return;
Bubble(a, len); /* first move first element to last */
Reverse(a, --len); /* now reverse the initial portition of bubbled array*/
}
#include <iostream>
using namespace std;
void reverse_array(int array[], int index, int len) {
if (index >= len - 1) return;
array[index] = array[index]^array[len - 1];
array[len - 1] = array[index]^array[len - 1];
array[index] = array[index]^array[len - 1];
reverse_array(array, index + 1, len - 1);
}
int main() {
int array[10];
for (int i = 0; i < 10; ++i)
array[i] = i;
reverse_array(array, 0, 10);
for (int i = 0; i < 10; ++i)
cout << array[i] << endl;
}
#include "stdio.h"
#define MAX 10
void printarr(int a[],int n)
{
printf("\nArray elements : ");
int i;
for(i=0;i<n;i++)
printf(" %d",a[i]);
}
void reverse(int a[],int start,int end)
{
int temp;
temp=a[start];
a[start]=a[end];
a[end]=temp;
if(start==end ||start==end-1)
return;
reverse(a,start+1,end-1);
}
int main()
{
int arr[MAX];
int n,i;
printf("Enter size of array : ");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter element : ");
scanf("%d",&arr[i]);
}
printarr(arr,n);
reverse(arr,0,n-1);
printarr(arr,n);
}

Silly question.
- Anonymous on May 02, 2012 Edit | Flag Replyvoid reverse(int *a, int n) { if (n <= 0) return; swap(a[0], a[n-1]); reverse(++a, n-1); }