Reverse the array/string.
Given an array (or string), the task is to reverse the array/string.
Examples :
Input : arr[] = {1, 2, 3} Output : arr[] = {3, 2, 1} Input : arr[] = {4, 5, 1, 2} Output : arr[] = {2, 1, 5, 4}
1) Initialize start and end indexes as start = 0, end = n-1
2) In a loop, swap arr[start] with arr[end] and change start and end as follows :
start = start +1, end = end – 1
Another example to reverse a string:
Below is the implementation of the above approach :
// Iterative C# program to reverse an
// array
using System;
class GFG {
/* Function to reverse arr[] from
start to end*/
static void rvereseArray(int []arr,
int start, int end)
{
int temp;
while (start < end)
{
temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
start++;
end--;
}
}
/* Utility that prints out an
array on a line */
static void printArray(int []arr,
int size)
{
for (int i = 0; i < size; i++)
Console.Write(arr[i] + " ");
Console.WriteLine();
}
// Driver function
public static void Main()
{
int []arr = {26,7,56,89,34,45,89};
printArray(arr, 6);
rvereseArray(arr, 0, 5);
Console.Write("Reversed array is \n");
printArray(arr, 6);
}
}
// This code is contributed by Anil Dwivedi
Output :
26 7 56 89 34 45 Reversed array is 45 34 89 56 7 26
Comments
Post a Comment