☕ Java

Sortieralgorithmen in Java: Eine ausführliche Anleitung

What is it and why? (Real-life analogy)

Imagine you are a librarian. Every day, dozens of new books arrive at the library. They need to be arranged on shelves in alphabetical order. If you just pile the books up, the reader will never find the right one. But if you take the time and arrange everything in order — the search becomes a matter of seconds.

Sorting in programming is exactly the same thing. It is the process of ordering data according to a specific rule (most often — ascending or descending). It is impossible to imagine any serious program without sorting: search, databases, internet recommendations, train schedules — everywhere data must be ordered.

Remember the main rule: sorting turns chaos into order. And order means speed and efficiency of the program.

Imagine you have an array of numbers: [5, 3, 8, 1, 9]. After sorting in ascending order, it will become [1, 3, 5, 8, 9]. Now you can find the number 8 in one glance, instead of iterating through all the elements.

In real life, we constantly sort: we arrange clothes by color, put books by size, line people up by height. Sorting algorithms are just formalized ways of doing the same thing, but for a computer.

Theory: how it works from the inside

To understand sorting, you need to understand three key concepts: comparison, swap, and complexity.

Comparison and Swap

Any sorting algorithm does two things:

  • Compares two elements (e.g., 5 > 3?)
  • Swaps them if the order is violated

In Java, comparison is done with operators <, >, == or via the compareTo() method for objects. Swapping is done using a temporary variable:

int temp = a;  // save the first number
a = b;         // put the second number in the first's place
b = temp;      // put the saved first number in the second's place

Algorithm Complexity (Big O)

This is a way to measure how fast an algorithm works. Imagine you have 1000 numbers. One algorithm will do 500,000 operations, while another will do only 10,000. The difference is colossal!

Notation Name Example for 1000 elements
O(n²) Quadratic ~1,000,000 operations (Bubble Sort)
O(n log n) Logarithmic ~10,000 operations (Quick Sort)
O(n) Linear ~1000 operations (ideal, but rare)
Important: O(n²) is slow. O(n log n) is fast. For small arrays (up to 100 elements) the difference is negligible, but for large data, the choice of algorithm is critical.

Sorting Stability

If two elements are equal, will they retain their original order? If yes — the sorting is stable. This is important when sorting complex objects (e.g., first by name, then by age).

Syntax in Java: all forms and options

Java provides several ways to sort. From the simplest (for beginners) to professional (for production).

1. Arrays.sort() — for arrays

The simplest way. Uses Dual-Pivot Quicksort for primitives and TimSort for objects.

import java.util.Arrays;

int[] numbers = {5, 3, 8, 1, 9};
Arrays.sort(numbers);  // now numbers = [1, 3, 5, 8, 9]

2. Collections.sort() — for lists

For ArrayList, LinkedList, and other collections:

import java.util.ArrayList;
import java.util.Collections;

ArrayList<String> names = new ArrayList<>();
names.add("Ivan");
names.add("Anna");
names.add("Pyotr");
Collections.sort(names);  // [Anna, Ivan, Pyotr]

3. Sorting in reverse order

Use Comparator.reverseOrder():

Arrays.sort(numbers);  // ascending order
// for reverse order:
Integer[] nums = {5, 3, 8, 1, 9};
Arrays.sort(nums, Collections.reverseOrder());  // [9, 8, 5, 3, 1]
Note: reverseOrder() only works with objects (Integer, String), not with primitives (int).

4. Sorting objects by fields

Suppose we have a class Student with fields name and grade. We want to sort students by grades:

import java.util.*;

class Student {
    String name;
    int grade;
    
    Student(String name, int grade) {
        this.name = name;
        this.grade = grade;
    }
}

// Sorting via Comparator
Collections.sort(students, new Comparator<Student>() {
    @Override
    public int compare(Student s1, Student s2) {
        return Integer.compare(s1.grade, s2.grade);
    }
});

// Or via lambda (modern way):
students.sort((s1, s2) -> Integer.compare(s1.grade, s2.grade));

5. Sorting via Stream API

Modern functional style (Java 8+):

List<Integer> sortedList = numbers.stream()
    .sorted()
    .collect(Collectors.toList());

// Sorting objects by field:
List<Student> sortedStudents = students.stream()
    .sorted(Comparator.comparingInt(s -> s.grade))
    .collect(Collectors.toList());

Code examples — from simple to complex

Example 1: Bubble Sort

The simplest to understand, but slow. Adjacent elements are compared and swapped if the order