Answers for "array reverse in groups of m in c"

C
0

array reverse in groups of m in c

#include<stdio.h>

// Function to reverse every sub-array
// formed by consecutive k elements
void ReverseInGroup(int arr[], int n, int k)
{
	if(n<k)
	{
	k=n;
	}

	// Initialize variables
	int d = k-1, m=2;
	int i = 0;
		
	for (i = 0; i < n; i++)
	{
		if (i >= d)
		{
			// Update the variables
			d = k * (m);
			if(d>=n)
			{
				d = n;			
			}		
			i = k * (m - 1)-1;
			m++;
			
		}
		else
		{
			int t = arr[i];
			arr[i] = arr[d];
			arr[d] = t;
		}

	d = d - 1;	
		
	}
	return;
		
}

// Driver code
int main()
{
	int arr[] = {1, 2, 3, 4, 5, 6, 7};
	int k = 4;

	int n = sizeof(arr) / sizeof(arr[0]);

	ReverseInGroup(arr, n, k);

	for (int i = 0; i < n; i++)
		printf("%d ", arr[i]);

	return 0;
}
Posted by: Guest on August-21-2021

Code answers related to "C"

Browse Popular Code Answers by Language