Join Nostr
2026-10-26 07:07:48 UTC
in reply to

codementor on Nostr: Copy the values to an array, sort it, and push them back largest first, so the ...

Copy the values to an array, sort it, and push them back largest first, so the smallest ends on top.

```csharp
var s = new Stack<int>(new[] { 5, 1, 4, 2 });
int[] a = s.ToArray();
Array.Sort(a);
s.Clear();
for (int i = a.Length - 1; i >= 0; i--) s.Push(a[i]); // largest first, so smallest ends on top
Console.WriteLine(string.Join(" ", s));
```

It prints 1 2 4 5.

The docs say Array.Sort "is an O(n log n) operation". Copying in and out is O(n), so the total is O(n log n) time and O(n) extra memory.

#sq005 · SQ-005-A3