Back to Practice Dashboard
Python BasicsEasy

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

Easy

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.

Constraints
  • 1 <= len(arr) <= 10^5
  • -10^9 <= arr[i] <= 10^9

Examples

Example 1
Input
arr = [5, 2, 8, 1, 4, 7]
Output
[1, 2, 5, 8, 7, 4]
Explanation

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].

Example 2
Input
arr = [3, 1, 2, 5, 4]
Output
[1, 2, 3, 5, 4]
Explanation

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].

Example 3
Input
arr = [9, 3, 6, 1]
Output
[3, 9, 6, 1]
Explanation

First half [9,3] ascending: [3,9]. Second half [6,1] descending: [6,1]. Result: [3,9,6,1].

Need a Hint?
Use simple arithmetic operators (like modulo `%`, division `//`), conditional checks, or loops to inspect number properties.
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.

Open in Editor