Sort an Array (Built-in vs Custom Comparator)

Sort an Array (LeetCode 912): how to use built-in sorts and custom comparators in Python, Java and C++, including ascending, descending and key-based ordering.

Problem Statement

Given an array nums, return it sorted in ascending order. In interviews you are often asked to also sort by custom rules (descending, by absolute value, by a key), which is what library sorts and comparators are for.

Example

Input:  nums = [5, 2, 3, 1]
Output: [1, 2, 3, 5]

Approach

Every major language ships an optimised O(n log n) sort. Pass a key or comparator to control the order. Note the stability difference: Python’s Timsort and Java’s Arrays.sort on objects are stable, while C++ std::sort (introsort) is not — use std::stable_sort when stability matters.

Complexity

  • Time: O(n log n)
  • Space: O(log n) to O(n) depending on implementation

Solution Code

Python

nums.sort()                    # ascending, in place, stable (Timsort)
nums.sort(reverse=True)        # descending
nums.sort(key=abs)             # by a key (absolute value)

from functools import cmp_to_key
nums.sort(key=cmp_to_key(lambda a, b: a - b))   # custom comparator

Java

Integer[] nums = {5, 2, 3, 1};
Arrays.sort(nums);                               // natural ascending (stable)
Arrays.sort(nums, Collections.reverseOrder());   // descending
Arrays.sort(nums, (a, b) -> Integer.compare(a, b)); // custom comparator
// int[] primitives: Arrays.sort(prim) is a (non-stable) dual-pivot quicksort

C++

vector<int> nums = {5, 2, 3, 1};
sort(nums.begin(), nums.end());                      // ascending (introsort)
sort(nums.begin(), nums.end(), greater<int>());      // descending
sort(nums.begin(), nums.end(),
     [](int a, int b){ return a < b; });             // custom comparator
stable_sort(nums.begin(), nums.end());               // use when stability matters

Key Takeaways

  • Prefer the library sort unless you have a specific reason not to.
  • Comparator contract: return negative/zero/positive (Java) or a strict-weak-ordering bool (C++).
  • Reference: LeetCode 912; cppreference std::sort; Python list.sort.
Written by Lorens Mishra

Software Engineer Notes Management System Administrator

Discussion

0 comments
Sign in to join the discussion.

No comments yet. Be the first to say something.