Sort first half ascending and second half descending
Detailed guide and Python implementation for the 'Sort first half ascending and second half descending' problem.
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 input structures
- Single element inputs
- Large numerical bounds
Ready to Solve?
Open the problem in PyRun's browser-based Python editor. Your code runs fully offline — no server required.
Recommended Python Resources
Expand your knowledge with related interactive tutorials, cheat sheets, and code comparisons.
Python Try/Except & Error Handling
Prevent your Python scripts from crashing. Learn try, except, finally blocks and how to raise custom exceptions properly.
How to Sort a List in Python
Learn how to sort a list in Python using the sort() method and the sorted() function. Discover custom key sorting and reverse order examples.
Python pip Package Manager
Command-line reference guide for pip. Learn to install, upgrade, uninstall, and manage Python packages and dependencies.
Python vs JavaScript: Which Programming Language is Best?
A comprehensive comparison between Python and JavaScript. Explore syntax differences, performance, use cases (backend vs frontend), and coding examples.