Optimized bubble sort