@waigx It's too slow to ask for the max and min inside the for loop. Replacing this by number comparisons will be much faster. I first identified the two locations where the array starts getting misplaced. So this doesn't require to obtain max and min all the time. They only involve comparisons. Then I called one max and one min inside the subarray, and find out the positions where they should be placed. The code is similar to @chao_liu 's.