Dec 29, 2008

give you an array a, now you need to rearrange its sequence, such that a[i]>a[i-1] && a[i]>a[i+1] for i=1,3,5,...,

give you an array a, now you need to rearrange its sequence, such that a[i]>a[i-1] && a[i]>a[i+1] for i=1,3,5,...,
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