Open In App

Sort Even-Placed in Increasing and Odd-placed Elements in Decreasing Order – Python

Last Updated : 17 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

We need to sort the elements at even indices in increasing order and the elements at odd indices in decreasing order. For example, given a list [10, 3, 5, 8, 2, 7, 6, 1], the result should be [2, 8, 5, 7, 6, 3, 10, 1]. Let us explore different ways to achieve this in Python.

Using List Comprehension with Sorting

This method uses list comprehension to separate even-indexed and odd-indexed elements, sorts them independently, and reconstructs the list.

Python
arr = [10, 3, 5, 8, 2, 7, 6, 1]
even = sorted(arr[i] for i in range(len(arr)) if i % 2 == 0)
odd = sorted((arr[i] for i in range(len(arr)) if i % 2 != 0), reverse=True)

res = [even.pop(0) if i % 2 == 0 else odd.pop(0) for i in range(len(arr))]

print("Resultant list:", res)

Output
Resultant list: [2, 8, 5, 7, 6, 3, 10, 1]

Explanation:

  • even contains elements at even indices sorted in increasing order.
  • odd contains elements at odd indices sorted in decreasing order.
  • The list is reconstructed by alternating elements from even and odd.

Using zip() with Separate Sorting

This method uses slicing along with zip() to extract even and odd indexed elements, sorts them and then combines them back.

Python
arr = [10, 3, 5, 8, 2, 7, 6, 1]

even = sorted(arr[::2]) 
odd = sorted(arr[1::2], reverse=True)

res = [even.pop(0) if i % 2 == 0 else odd.pop(0) for i in range(len(arr))]
print("Resultant list:", res)

Output
Resultant list: [2, 8, 5, 7, 6, 3, 10, 1]

Explanation:

  • Slicing directly extracts even and odd indexed elements.
  • These slices are sorted separately and then combined.

Using Itertools

For Index-Based Reconstruction this method uses iterators to alternate between sorted lists during reconstruction.

Python
from itertools import cycle

arr = [10, 3, 5, 8, 2, 7, 6, 1]

even = iter(sorted(arr[::2])) 
odd = iter(sorted(arr[1::2], reverse=True))
res = [next(even) if i % 2 == 0 else next(odd) for i in range(len(arr))]
print(res)

Output
Resultant list: [2, 8, 5, 7, 6, 3, 10, 1]

Explanation:

  • Iterators ensure efficient traversal of sorted elements.
  • The list is reconstructed by alternating between even and odd indexed elements.

Using Heap

This method uses heaps for sorting elements efficiently.

Python
import heapq

arr = [10, 3, 5, 8, 2, 7, 6, 1]

even = [arr[i] for i in range(len(arr)) if i % 2 == 0]
odd = [arr[i] for i in range(len(arr)) if i % 2 != 0]

heapq.heapify(even) 
heapq._heapify_max(odd)

result = [] 
for i in range(len(arr)): 
  if i % 2 == 0: result.append(heapq.heappop(even)) 
else: 
  res.append(heapq._heappop_max(odd))
print(res)

Output
Resultant list: [2, 5, 6, 10, 8]

Explanation:

  • Heaps are used for efficient sorting of elements.
  • Elements are extracted alternately to reconstruct the list.


Next Article
Practice Tags :

Similar Reads