Skip to main content
Back to problems
#2164
Easy Algorithms

Sort even and odd indices independently

Array Sorting
63.2% acceptance
Feb 25, 2026
798
70
You are given a 0-indexed integer array nums. Rearrange the values of nums according to: Sort values at odd indices in non-increasing order. Sort values at even indices in non-decreasing order. Return the array after rearranging.

Solution

Rust
Time O(n log n)
Space O(n)
LeetCode
solution.rs
impl Solution {
  pub fn sort_even_odd(nums: Vec<i32>) -> Vec<i32> {
    let mut evens: Vec<i32> = nums.iter().step_by(2).cloned().collect();
    let mut odds: Vec<i32> = nums.iter().skip(1).step_by(2).cloned().collect();
    evens.sort_unstable();
    odds.sort_unstable_by(|a, b| b.cmp(a));
    let mut result = Vec::with_capacity(nums.len());
    let mut ei = 0;
    let mut oi = 0;
    for i in 0..nums.len() {
      if i % 2 == 0 {
        result.push(evens[ei]);
        ei += 1;
      } else {
        result.push(odds[oi]);
        oi += 1;
      }
    }
    result
  }
}