🔃 Sorting
Sorting
Default sort, custom comparator, sort by key
Sorting with a custom comparator is essential in interviews — e.g. by second element, by length, or descending.
Language:
Python
Loading...
All languages — Default sort
JavaScript
const nums = [3, 1, 4, 1, 5, 9, 2, 6];
// ACHTUNG: sort() konvertiert zu Strings by default!
nums.sort(); // FALSCH für Zahlen: [1,1,2,3,4,5,6,9] ← zufällig ok
nums.sort((a, b) => a - b); // Aufsteigend ✓
nums.sort((a, b) => b - a); // Absteigend
const sorted = [...nums].sort((a, b) => a - b); // nicht in-placeTypeScript
const nums: number[] = [3, 1, 4, 1, 5, 9, 2, 6];
nums.sort((a, b) => a - b); // aufsteigend
nums.sort((a, b) => b - a); // absteigend
const sorted: number[] = [...nums].sort((a, b) => a - b);Java
int[] nums = {3, 1, 4, 1, 5, 9};
Arrays.sort(nums); // in-place, aufsteigend
// Für absteigend — braucht Integer[]:
Integer[] nums2 = {3, 1, 4, 1, 5, 9};
Arrays.sort(nums2, Comparator.reverseOrder());
// List:
List<Integer> list = new ArrayList<>(Arrays.asList(3,1,4));
Collections.sort(list);
list.sort(Comparator.reverseOrder());Go
import "sort"
nums := []int{3, 1, 4, 1, 5, 9, 2, 6}
sort.Ints(nums) // aufsteigend, in-place
sort.Sort(sort.Reverse(sort.IntSlice(nums))) // absteigend
// Kopie sortieren:
sorted := make([]int, len(nums))
copy(sorted, nums)
sort.Ints(sorted)C++
#include <algorithm>
vector<int> nums = {3, 1, 4, 1, 5, 9, 2, 6};
sort(nums.begin(), nums.end()); // aufsteigend
sort(nums.begin(), nums.end(), greater<int>()); // absteigend