last = -1for i = 0 to n-1 j = n-1 k = i if last > 0 && last > i k = last while (j > k) if (x[j-1] > x[j]) swap(x, j-1, j) last = j j-- if last == k break