Question:
Write a program to reverse an array or string?.
Solution:(Recursively)
1) Initialize start and end indexes
start = 0, end = n-1
2) Swap arr[start] with arr[end]
3) Recursively call reverse for rest of the array.
Sample Code:
/**
* @author Abhinaw.Tripathi
*
*/
public class ReverseArray
{
public static void reverse(int arr[],int start,int end)
{
int temp;
if(start>=end)
return;
temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
reverse(arr, start+1, end-1);
}
public static void printArray(int arr[], int size)
{
for (int i=0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6};
printArray(arr, 6);
reverse(arr, 0, 5);
System.out.println("Reversed array is ");
printArray(arr, 6);
}
}
Output:
1 2 3 4 5 6
Reversed array is
6 5 4 3 2 1
Time Complexity: O(n)
Write a program to reverse an array or string?.
Solution:(Recursively)
1) Initialize start and end indexes
start = 0, end = n-1
2) Swap arr[start] with arr[end]
3) Recursively call reverse for rest of the array.
Sample Code:
/**
* @author Abhinaw.Tripathi
*
*/
public class ReverseArray
{
public static void reverse(int arr[],int start,int end)
{
int temp;
if(start>=end)
return;
temp=arr[start];
arr[start]=arr[end];
arr[end]=temp;
reverse(arr, start+1, end-1);
}
public static void printArray(int arr[], int size)
{
for (int i=0; i < size; i++)
System.out.print(arr[i] + " ");
System.out.println("");
}
public static void main(String[] args)
{
int arr[] = {1, 2, 3, 4, 5, 6};
printArray(arr, 6);
reverse(arr, 0, 5);
System.out.println("Reversed array is ");
printArray(arr, 6);
}
}
Output:
1 2 3 4 5 6
Reversed array is
6 5 4 3 2 1
Time Complexity: O(n)
No comments:
Post a Comment