Refactored SortArray logic to improve efficiency and clarity.