optimization of bubble sort to prevent unnecessary  iterations