Programming
Arrays
Sorting Algorithms
Computer Science
Integer Manipulation

How to sort an array of integers?

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

Sorting an integer array is a common task in backend services, analytics pipelines, and interview problems. The right approach depends on data size, memory constraints, and whether you need stable ordering for equal values. In practice, built in sort functions are usually best, but understanding algorithm tradeoffs helps when performance matters.

Use Built-In Sort First

Most languages ship highly optimized sorting implementations that are faster and safer than handwritten algorithms for general use.

Python example:

python
1numbers = [42, 7, -3, 19, 19, 0, 8]
2numbers.sort()  # in place ascending
3print(numbers)
4
5numbers_desc = sorted(numbers, reverse=True)  # new list
6print(numbers_desc)

Why built in sort is usually the default:

  • Well tested for edge cases.
  • Optimized in C or runtime internals.
  • Clear intent in code review.

Only replace it when you have a specific algorithmic reason.

Know Core Algorithm Options

You should still know major sorting families so you can choose correctly when constraints are explicit.

Insertion sort:

  • Good for tiny arrays.
  • Great when data is nearly sorted.
  • Simple implementation.

Merge sort:

  • Predictable O(n log n) time.
  • Stable sort behavior.
  • Uses extra memory.

Quick sort:

  • Usually fast in practice.
  • In place variants use little extra memory.
  • Worst case can degrade to quadratic time if pivot selection is poor.

Here is a simple insertion sort for learning:

python
1def insertion_sort(arr):
2    a = arr[:]  # copy so input remains unchanged
3    for i in range(1, len(a)):
4        key = a[i]
5        j = i - 1
6        while j >= 0 and a[j] > key:
7            a[j + 1] = a[j]
8            j -= 1
9        a[j + 1] = key
10    return a
11
12print(insertion_sort([9, 4, 7, 1, 3]))

Use this for understanding, not for large production arrays where built in sort already does better.

Choose by Data Characteristics

Data characteristics often matter more than algorithm names.

Questions to ask:

  • Is the array small or huge.
  • Is it already almost sorted.
  • Are duplicates common.
  • Do equal values need stable relative order.
  • Can you afford extra memory.

Example strategy:

  • For application code: use built in sort.
  • For streaming chunks: sort chunks then merge.
  • For tight memory: prefer in place methods with careful benchmarking.

If integer values are from a small bounded range, counting sort can beat comparison sorts.

python
1def counting_sort(arr, max_value):
2    counts = [0] * (max_value + 1)
3    for x in arr:
4        counts[x] += 1
5
6    out = []
7    for value, count in enumerate(counts):
8        out.extend([value] * count)
9    return out
10
11print(counting_sort([4, 2, 2, 8, 3, 3, 1], max_value=8))

Counting sort is linear in value range plus input length, but only suitable when range size is manageable and values are non negative integers.

Validate Correctness and Performance

When sorting is on a hot path, test both correctness and speed.

Correctness checks:

  • Empty array.
  • One element.
  • Already sorted.
  • Reverse sorted.
  • Many duplicate values.

Simple benchmark structure in Python:

python
1import random
2import time
3
4data = [random.randint(-10_000, 10_000) for _ in range(200_000)]
5start = time.perf_counter()
6sorted_data = sorted(data)
7elapsed = time.perf_counter() - start
8print(f"sorted {len(data)} integers in {elapsed:.4f} seconds")
9print(sorted_data[:5], sorted_data[-5:])

Use realistic distributions instead of toy arrays so benchmark results match production behavior.

Common Pitfalls

  • Reimplementing sort in production without a measurable need.
  • Ignoring stability requirements when equal keys exist.
  • Benchmarking with tiny arrays and drawing broad conclusions.
  • Mutating input unexpectedly when callers expect an immutable workflow.
  • Forgetting negative numbers or duplicate handling in custom algorithms.

Summary

  • Start with built in sort for safety, performance, and readability.
  • Choose custom algorithms only when constraints justify the extra complexity.
  • Match algorithm choice to data size, distribution, and memory limits.
  • Validate with edge case tests and realistic benchmarks.
  • Document whether sorting is in place or returns a new array.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.