Advertisement
Advanced C#, Arrays, Span<T> & Memory<T>

How would you use Span<T> to implement an in-place array reversal or sorting algorithm without allocating a temporary array?

Short answer

Span supports the same indexed read/write access as a regular array with none of the allocation overhead of copying — algorithms like in-place reversal or a custom sort can operate directly on a Span (or a slice of one), swapping elements by index exactly as you would on a raw…

Save C# mock interview
Advertisement
AModel answer
Span<T> supports the same indexed read/write access as a regular array with none of the allocation overhead of copying — algorithms like in-place reversal or a custom sort can operate directly on a Span<T> (or a slice of one), swapping elements by index exactly as you would on a raw array, but with the added flexibility of it being a VIEW that could point into a larger buffer.
void ReverseInPlace(Span<int> span) {
  int left = 0, right = span.Length - 1;
  while (left < right) {
    (span[left], span[right]) = (span[right], span[left]);
    left++; right--;
  }
}
int[] arr = { 1, 2, 3, 4, 5 };
ReverseInPlace(arr.AsSpan()); // arr is now { 5, 4, 3, 2, 1 }, zero extra allocation
Real-world example
Implementing performance-critical, allocation-free array manipulation utilities in a numeric or data-processing library.
Likely follow-ups
  • Could this same ReverseInPlace function also operate directly on memory allocated via stackalloc?
Related topics