Reverse an array in groups of given size - GeeksforGeeks
Given an array, reverse every sub-array formed by consecutive k elements.
http://www.geeksforgeeks.org/reverse-an-array-in-groups-of-given-size-2/
Read full article from Reverse an array in groups of given size - GeeksforGeeks
Given an array, reverse every sub-array formed by consecutive k elements.
The idea is very simple. We consider every sub-array of size k starting from beginning of the array and reverse it. We need to handle some special cases. If k is not multiple of n where n is size of the array, for last group we will have less than k elements left, we need to reverse all remaining elements. If k = 1, array should remain unchanged. If k >= n, we reverse all elements present in the array.
void
reverse(
int
arr[],
int
n,
int
k)
{
for
(
int
i = 0; i < n; i += k)
{
int
left = i;
// to handle case when k is not multiple of n
int
right = min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while
(left < right)
swap(arr[left++], arr[right--]);
}
}
http://www.geeksforgeeks.org/reverse-an-array-in-groups-of-given-size-2/
Variation 1: Reverse every alternate sub-array formed by consecutive k elements.
void
reverse(
int
arr[],
int
n,
int
k)
{
// increment i in multiples of 2*k
for
(
int
i = 0; i < n; i += 2*k)
{
int
left = i;
// to handle case when 2*k is not multiple of n
int
right = min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while
(left < right)
swap(arr[left++], arr[right--]);
}
}
Variation 2: Reverse every sub-array formed by consecutive k elements at given distance apart.
Examples:
Examples:
Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] k = 3 m = 2 Output: [3, 2, 1, 4, 5, 8, 7, 6, 9, 10]
void
reverse(
int
arr[],
int
n,
int
k,
int
m)
{
// increment i in multiples of k + m
for
(
int
i = 0; i < n; i += k + m)
{
int
left = i;
// to handle case when k + m is not multiple of n
int
right = min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while
(left < right)
swap(arr[left++], arr[right--]);
}
}
Variation 3: Reverse every sub-array formed by consecutive k elements where k doubles itself with every sub-array.
Examples:
Examples:
Input: arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] k = 1 Output: [1], [3, 2], [7, 6, 5, 4], [15, 14, 13, 12, 11, 10, 9, 8]
void
reverse(
int
arr[],
int
n,
int
k)
{
// increment i in multiples of k where value
// of k is doubled with each iteration
for
(
int
i = 0; i < n; i += k/2)
{
int
left = i;
// to handle case when number of elements in
// last group is less than k
int
right = min(i + k - 1, n - 1);
// reverse the sub-array [left, right]
while
(left < right)
swap(arr[left++], arr[right--]);
// double value of k with each iteration
k = k*2;
}
}