using System;
/*
You have an array containing integers, and you have a reference number.
Example:
Array = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20}
Reference = 10
You have to sort the array, based on the distance from the reference number, from the closest to the most distant, and get a result similar to this:
{10,9,11,8,12,7,13,6,14,5,15,4,16,3,17,2,18,1,19,20}
The input sequence can be different and random, there may be duplicate numbers. Different outputs can be valid, in the example also the sequence that starts with {10,11,9 ...}.
Another example to test your algorithm:
Reference = 25
Input: {11,7,42,7,3,8,5,48,24,45,32,21}
Output: {24,21,32,11,8,42,7,7,5,45,3,48}
The winner will be the one who writes the algorithm that does this faster. I will do a benchmark test to test the speed.
Send me the solution privately so the others don't copy it
You can take this code as a base and complete it:
*/
public class Program
{
public static readonly int[] Ar = { 7, 13, 2, 16, 20, 1, 0, 11, 1, 5, 13, 17, 6, 15, 20, 1, 1, 14, 13, 8, 6, 4, 10, 4, 4, 20, 10, 19, 6, 11, 8, 8, 12, 15, 6, 9, 15, 6, 11, 19, 18, 12, 14, 11, 17, 18, 9, 10, 10, 15, 12, 17, 0, 1, 11 };
//public static readonly int[] Ar = {5, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20 };
public static void Main()
int[] a = Ar;
int rif=10;
RelativeOrder(a, rif);
int[] dist = new int[a.Length];
for (int k = 0; k<a.Length; k++)
dist[k] = Math.Abs(a[k] - rif);
}
for (int i=0; i<a.Length; i++)
Console.WriteLine("DIST: " + dist[i] +"\t VALUE: " + a[i] + "\n");
public static int[] RelativeOrder(int [] v, int rif)
int[] dist = new int[v.Length];
int maxDistance = 0;
for (int k = 0; k<v.Length; k++)
dist[k] = Math.Abs(v[k] - rif);
if (maxDistance < dist[k])
maxDistance = dist[k];
int[] filledElements = new int[maxDistance +1];
int[][] slices = new int[maxDistance + 1 ][];
for (int i=0; i<maxDistance +1; i++)
slices[i] = new int[v.Length];
for (int i=0; i<dist.Length; i++)
slices[dist[i]][filledElements[dist[i]]] = v[i];
filledElements[dist[i]]++;
int jj = 0;
for (int i=0; i<slices.Length; i++)
for (int j=0; j<filledElements[i]; j++)
v[jj++] = slices[i][j];
return v;