Given an array of a positive integer, we need to exchange each element with the first element that is smaller than it (the current element) when moving from left to right.
Example
{ 3 , 5 , 12, 2 ,11 } { 2 , 3 , 5 , 11, 12 }
Brute force simulation for a better understanding of the problem
{ 5, 11, 2, 7, 2 } After first exchange { 2, 11, 5, 7, 2} After second exchange { 2, 5, 11, 7, 2} After third exchange { 2, 5, 7, 11, 2} After fourth exchange { 2, 5, 7, 2, 11}
Can anyone think of a solution that is better than O (n ^ 2). At first I thought about maintaining a double-ended queue, and when we travel from the first element to the right, we can try to keep the next smallest element of the other between them.
As in the first case, I will do something like this
while i am finding next element of 3, I will maintain a curr_next to 5. If before encountering the next small element for 3, i encounter one of 5, then I will enqueue it but it hardly improve the performance and still O(n^2)
EDIT: we need to move from left to right. Modeling the first example -
{ _3_ , 5 , 12, 2 ,11 } { 2, _5- , 12, 3, 11 } { 2, 3, _12_ , 5, 11 } { 2, 3, 5, _12_, 11 } { 2, 3, 5, 11 , 12 }