BUG: Fix out-of-bounds access in safe_sort with an empty array and non-empty codes
`safe_sort` could handle out-of-bounds references in `codes` so long as the array was not empty.
By masking all out-of-bounds values to -1, we can handle both empty and non-empty array cases.
Previously we masked out-of-bounds values to 0 and then fixed them up afterwards, but this results in accessing the 0th element which doesn't exist in the empty array case.

- [x] closes #59421
- [x] [Tests added and passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#writing-tests) if fixing a bug or adding a new feature
- [x] All [code checks passed](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#pre-commit).
- [x] Added [type annotations](https://pandas.pydata.org/pandas-docs/dev/development/contributing_codebase.html#type-hints) to new arguments/methods/functions.
- [x] Added an entry in the latest `doc/source/whatsnew/vX.X.X.rst` file if fixing a bug or adding a new feature.

> Could you also add a unit test for your original example in [#59421 (comment)](https://github.com/pandas-dev/pandas/issues/59421#issue-2449172337)?

Done. I also verified that with bounds checking enabled on `take_1d_*`, this additional test failed at HEAD and passes with the changes in this PR. Thanks @jsspencer 