Logo

How to sort an array of integers?

Sorting an array of integers is a ubiquitous task in programming. While some languages have built-in sort functions, it’s still important to know the details—like time complexity, sorting order, and custom comparator functions—especially if you’re preparing for interviews or working with large datasets. Below, we’ll explore how to sort an array of integers in different contexts, discuss relevant time complexities, and provide some interview tips to help you stand out.

1. Sorting in JavaScript

Using the Built-in sort() Method

In JavaScript, the simplest way to sort an array of integers is with the built-in Array.prototype.sort() method. By default, sort() will convert elements to strings and compare them lexicographically (i.e., "10" comes before "2"). To properly sort numbers, you need to provide a comparator function:

const numbers = [10, 2, 5, 9, 30, 1]; // Sort in ascending order numbers.sort((a, b) => a - b); console.log(numbers); // Output: [1, 2, 5, 9, 10, 30]
  • Explanation:
    • (a, b) => a - b returns a negative value if a < b, zero if a === b, and a positive value if a > b.
    • JavaScript’s sort() method uses this result to determine which element comes first.

Custom Sort Orders

To sort in descending order, simply reverse the subtraction:

numbers.sort((a, b) => b - a);

Time Complexity

  • Average & Worst Case: O(n log n) for most sorting implementations in JavaScript (like V8’s Timsort).

2. Sorting in Other Languages

Python

nums = [10, 2, 5, 9, 30, 1] nums.sort() # In-place sort (ascending) print(nums) # [1, 2, 5, 9, 10, 30]
  • Custom Order: Use nums.sort(reverse=True) for descending or sorted(nums, reverse=True) to create a new sorted list.

Java

import java.util.Arrays; int[] numbers = {10, 2, 5, 9, 30, 1}; Arrays.sort(numbers); System.out.println(Arrays.toString(numbers)); // Output: [1, 2, 5, 9, 10, 30]
  • For descending order, you’d typically convert to a List<Integer> and use a custom comparator or reverse the array after a normal sort.

C++ (Using STL)

#include <bits/stdc++.h> using namespace std; int main() { vector<int> numbers = {10, 2, 5, 9, 30, 1}; sort(numbers.begin(), numbers.end()); // Ascending // sort(numbers.begin(), numbers.end(), greater<int>()); // Descending for (auto num : numbers) { cout << num << " "; } return 0; }

3. Manual Sorting Algorithms (When You Need Them)

While built-in methods are reliable, you might encounter interview questions or special constraints where you need to implement sorting algorithms (like QuickSort, MergeSort, or HeapSort):

  1. QuickSort
    • Average O(n log n), worst-case O(n²) if the pivot is poorly chosen.
  2. MergeSort
    • Average & worst-case O(n log n), stable sorting but requires O(n) extra space.
  3. HeapSort
    • Always O(n log n) in worst-case, often used in memory-constrained environments.

Interview Tip: Be prepared to analyze these algorithms’ time and space complexities and know how to write or at least describe the approach in detail.

4. Interview & Real-World Tips

  1. Big-O Notation: Built-in sorts generally implement an optimized version of O(n log n). Always mention time complexity in interviews.
  2. Stability: Some sorting algorithms (like MergeSort) are stable, meaning equal elements maintain their original order. Check if your language’s default sort is stable (JavaScript’s Timsort is stable, for example).
  3. Data Size: For extremely large arrays, also consider memory overhead. If you only need partial sorting (like the top K elements), you might use a min-heap or partial sort to reduce complexity.
  4. Edge Cases:
    • Empty arrays ([]).
    • Arrays with negative numbers or large integers.
    • Arrays with duplicate values—stability might matter if these are objects with additional properties.

5. Level Up Your Coding & Interview Skills

If you’re preparing for interviews or looking to strengthen your understanding of sorting and other algorithmic essentials, we recommend checking out these courses from DesignGurus.io:

To further sharpen your skills, consider signing up for a Coding Mock Interview session with ex-FAANG engineers. You can also explore the DesignGurus YouTube Channel for free tutorials, interview tips, and more.

Final Thoughts

Sorting integers is a classic operation encountered in nearly every programming domain. While built-in methods in languages like JavaScript (sort() with a comparator), Python (.sort() or sorted()), Java (Arrays.sort()), and C++ (std::sort) are typically your go-to, knowing their under-the-hood complexities and edge cases will make you a more confident engineer—especially in technical interviews. By combining this knowledge with a deeper understanding of sorting algorithms and when to apply them, you’ll be well-equipped to handle any sorting challenge that comes your way.

CONTRIBUTOR
TechGrind