BaluS
BaluS

Reputation: 55

Rearrange a sorted array

I have a sorted array in ascending order. I have to build a new array in such a way that the last element of the sorted array will be the first element of the new array and the first element of the sorted array will be next element of the new array and so on. For example-

//if a[] is the sorted array.
a[]={1,2,3,4,5}

//output-
//b[] is the new array.
b[]={5,1,4,2,3}

My approach is- Using two index i and j.

for (int i = 0, j = 0; j< count; i++, j++)
{
    b[j] = a[count - (i + 1)];
    b[++j] = a[i];
}

Now Question is how to do this using only a single index i.e using only index i from my example.

Thanks in advance!

Upvotes: 2

Views: 119

Answers (2)

Tony Delroy
Tony Delroy

Reputation: 106096

for (int i = 0; i < count; ++i)
    b[i] = a[i % 2 ? i / 2 : count - i / 2 - 1];

Explanation: i % 2 checks if the b index being set is at an odd 0-based position: if so it takes from a[i/2], otherwise it comes back the same i/2 amount from the end of a, which is a[count - 1], so a[count - i/2 - 1].

See it run here.

Upvotes: 4

Danh
Danh

Reputation: 6016

for (int i = 0; i < count / 2; i++)
{
    b[2*i] = a[count - (i + 1)];
    b[2 * i + 1] = a[i];
}
if (count % 2)
{
    b[count - 1] = a [count / 2];
}

Upvotes: 3

Related Questions