Note there might be many sequence of equal elements. of course it may be not able to be rearranged like that.
O(n) time and O(1) space
for(i = 1; i < n; i += 2) //this cannot handle 3 equal numbers consequential
{
if((a[i-1] == a[i]) && (a[i] == a[i+1]))
continue;
maximum = max3(a[i-1],a[i],a[i+1]);
if(maximum == a[i])
continue;
else if(maximum == a[i-1])
swap(input[i-1],input[i]);
else
swap(input[i],input[i+1]);
}
No comments:
Post a Comment