Optimized bubble sort function