tags:

views:

1220

answers:

6

Hi,

I have an array of n = 32 items with positive and negative values. First n/2 elements are positive and sorted by value and second n/2 elements are negative and sorted by value as well. I would like to sort the whole array by value, starting from the smallest negative value to biggest positive value which means if there are 32 elements the first 16 (n/2) sorted elements should contain the values of second 16 elements of the original array and the second 16 elements of the sorted array should contain the first 16 values of the original array.

Hypothetical example:

double[] original = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, -16, -15, ..., -1};

double[] sorted = {-16, -15, ...., -1, 1, 2, ..., 16};

Does anyone know what is the best way to shift the elements to generate the sorted array from original?

This array is by the way tied to another array which doesn't have the elements sorted by size the same way and has to be shifted the same way as original so the array shouldn't be sorted by size, it has to be shifted.

A: 

Just do a swap on element 0 and element 16, 1 and 17, 2 and 18.. etc.

Joe Philllips
A: 

Have you tried:

Array.Sort(original);
Darin Dimitrov
it has to be shifted not sorted!
niko
In the example you gave, the desired result will be obtained with Array.Sort.
Darin Dimitrov
Bearing in mind that both halves are already sorted (according to your description) shifting element 0 with 16, 1 and 17, 2 and 19, etc... will have the same result as sorting the array by size.
Darin Dimitrov
+4  A: 

So you want a second array, with the contents of the original but at locations shifted? Either do it explicitly:

double[] result = new double[32];
for (int i=0; i < 32; i++)
{
    result[(i+16)%32] = original[i];
}

or using Array.Copy twice:

double[] result = new double[32];
Array.Copy(original, 0, result, 16, 16);
Array.Copy(original, 16, result, 0, 16);
Jon Skeet
+1  A: 

How about in Linq:

int half = original.Length/2;
var sorted = original.Skip(half).Concat(original.Take(half)).ToArray();
Keltex
I think you mean Concat rather than Union - Union will remove any repeated elements.
Jon Skeet
@Jon: Thanks... I made your suggested change.
Keltex
A: 

Do you want to sort one array based on the values contained in another array of the same size? If so, use the following:

Array.Sort(keys, values);

Here's the documentation Array.Sort(Array keys, Array items)

Waylon Flinn
+1  A: 

Given the rigid nature of the problem, Array.Copy:

        int half = original.Length / 2;
        Array.Copy(original, 0, sorted, half, half);
        Array.Copy(original, half, sorted, 0, half);
Marc Gravell