Optimized bubble and merge sort functions