Implementing bucket-sort in Java or Python: why take entries off a LinkedList with removeFirst() or a deque with popleft(), and not off an ArrayList with remove(0) or a Python list with pop(0)?
Removing the first element of an array-backed list shifts all the others one place to the left, which costs $O(n)$ every time. Doing that for all $n$ entries makes phase 1 alone $O(n^2)$. A linked list or a deque removes its first element in $O(1)$, which keeps bucket-sort at $O(n + N)$.
The pseudo-code's sequence operations first(), remove() and insertLast() assume constant time at both ends. Which Java or Python type you pick decides whether that holds:
| Operation | Java | Python | Cost |
|---|---|---|---|
| remove the first element | ArrayList.remove(0) |
list.pop(0) |
$O(n)$: everything behind it moves |
| remove the first element | LinkedList.removeFirst() |
deque.popleft() |
$O(1)$ |
| append at the end | add(x) |
append(x) |
$O(1)$, amortised for array-backed lists |
Use the same queue types for the buckets, so that phase 2 can take from the front cheaply as well. If the input is an array, there is an even simpler route: read it from front to back with an ordinary loop instead of removing anything, and overwrite it with the collected entries in phase 2.
Go deeper:
Python documentation: collections.deque — O(1) appends and pops at both ends, and why
list.pop(0)is O(n).Java 21 API: ArrayList — which operations run in constant time and which in linear time.