Sort First Half in Ascending Order and Second Half in Descending

Understanding Sorting Strategy

This task involves sorting the first half of an array in ascending order and the second half in descending order.

We will explore three different methods to achieve this in Python.

Method 1: Using Slicing

This method splits the array into two halves and sorts them separately.

def sort_half(arr):
    mid = len(arr) // 2
    arr[:mid] = sorted(arr[:mid])
    arr[mid:] = sorted(arr[mid:], reverse=True)
    return arr

arr = [7, 2, 5, 3, 9, 8, 6, 4]
print(sort_half(arr))
            
Output:
[2, 3, 5, 7, 9, 8, 6, 4]

Method 2: Using a Single Loop

This method sorts the array manually within a single loop.

def sort_half(arr):
    mid = len(arr) // 2
    first_half = sorted(arr[:mid])
    second_half = sorted(arr[mid:], reverse=True)
    return first_half + second_half

arr = [7, 2, 5, 3, 9, 8, 6, 4]
print(sort_half(arr))
            
Output:
[2, 3, 5, 7, 9, 8, 6, 4]

Method 3: Using List Comprehension

This method utilizes list comprehension for efficient sorting.

def sort_half(arr):
    mid = len(arr) // 2
    return sorted(arr[:mid]) + sorted(arr[mid:], reverse=True)

arr = [7, 2, 5, 3, 9, 8, 6, 4]
print(sort_half(arr))
            
Output:
[2, 3, 5, 7, 9, 8, 6, 4]
Top 100 Codes By Learn-for-free
Start Preparing Arraysform here👇

Below You will find some of the most important codes in languages like C, C++, Java, and Python. These codes are of prime importance for college semester exams and online tests.

Getting Started

Find Largest Element in an Array: C C++ Java Python

Find Smallest Element in an Array: C C++ Java Python

Find the Smallest and Largest Element in an Array: C C++ Java Python

Find Second Smallest Element in an Array: C C++ Java Python

Calculate the Sum of Elements in an Array: C C++ Java Python

Reverse an Array: C C++ Java Python

Sort First Half in Ascending Order and Second Half in Descending: C C++ Java Python

Finding the Frequency of Elements in an Array: C C++ Java Python

Counting the Number of Even and Odd Elements in an Array: C C++ Java Python

Finding Maximum Product Sub-array in a Given Array: C C++ Java Python

Finding Arrays are Disjoint or Not: C C++ Java Python

Finding Equilibrium Index of an Array: C C++ Java Python

Rotation of Elements of Array - Left and Right: C C++ Java Python

Balanced Parenthesis Problem: C C++ Java Python