Sort first half ascending and second half descending
Learn how to solve the 'Sort first half ascending and second half descending' problem. This detailed resource details brute force and optimized approaches.
Problem Statement
Write a function sort_half(arr) that takes a list of integers and returns a new list where the first half is sorted in ascending order and the second half is sorted in descending order. If the array has odd length, the middle element belongs to the first half. For example, for length 5, the first 3 elements are sorted ascending and the last 2 are sorted descending.
- •1 <= len(arr) <= 10^5
- •-10^9 <= arr[i] <= 10^9
Examples
arr = [5, 2, 8, 1, 4, 7]
[1, 2, 5, 8, 7, 4]
First half [5,2,8] sorted ascending: [1,2,5]. Second half [1,4,7] sorted descending: [8,7,4]. Wait — we split the original array: first 3 elements [5,2,8] sort ascending -> [2,5,8], last 3 [1,4,7] sort descending -> [7,4,1]. Result: [2,5,8,7,4,1].
arr = [3, 1, 2, 5, 4]
[1, 2, 3, 5, 4]
First half (3 elements) [3,1,2] sorted ascending: [1,2,3]. Second half (2 elements) [5,4] sorted descending: [5,4]. Result: [1,2,3,5,4].
arr = [9, 3, 6, 1]
[3, 9, 6, 1]
First half [9,3] ascending: [3,9]. Second half [6,1] descending: [6,1]. Result: [3,9,6,1].
Need a Hint?
Edge Cases to Watch
- Empty list or null input variables
- Single item lists/arrays
- Extremely large input bounds causing integer or stack overflow
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.