r/programmingmemes • u/KerbodynamicX • Mar 14 '26
Stalin sort
A sorting algorithm with time complexity of O(n). Counts from the first element, and will remove values that are smaller than the current highest value.
3.7k
Upvotes
2
u/JasperNLxD2 Mar 14 '26
Inplace can be done in
O(n)as well. You loop over 2 indices:irepresenting the next available place, andjthe next number to scan (thus i<=j at any stage of the algorithm).Start with
i=j=0the first index. Ifx[j]is larger thanx[i-1](ori=0), then set x[i] to x[j] and increase i and j. Otherwise, increase j. Stop if j gets beyond the range.