Skip to content

Instantly share code, notes, and snippets.

@timxor
Created November 23, 2025 08:28
Show Gist options
  • Select an option

  • Save timxor/6d34137a74410bfeb947d6863f42b568 to your computer and use it in GitHub Desktop.

Select an option

Save timxor/6d34137a74410bfeb947d6863f42b568 to your computer and use it in GitHub Desktop.
Copy from both ends simultaneously toward the center.
// Bidirectional Copy (from both ends toward center)
// Used for reversing arrays or merging sorted arrays
// Processes from opposing ends simultaneously
public static void bidirectionalCopy(int[] src, int srcStart, int srcEnd,
int[] dest, int destStart, int destEnd) {
int left = srcStart;
int right = srcEnd;
int destLeft = destStart;
int destRight = destEnd;
while (left <= right) {
dest[destLeft++] = src[left++];
if (left <= right) {
dest[destRight--] = src[right--];
}
}
}
// Example: Reverse array elements
// Original: [1, 2, 3, 4, 5]
// Bidirectional copy from indices 0-4 to indices 4-0
// Result: [5, 4, 3, 2, 1] (reversed)
// Example: Merge sorted arrays
// Left half: [1, 3, 5]
// Right half: [2, 4, 6]
// Bidirectional merge works from both ends to build sorted result
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment