- You are not clearing the sorted array after the inner while loop, which is causing the elements to reappear in the result. To fix this, you can define the sorted array inside the while loop like this:
- Additionally, you cannot merge result and sorted arrays directly, since both arrays are sorted, you need to merge them in a sorted manner.