Re-order array putting zeros at the end of c #
I am trying to do LRU and keep track of the order of the values.
So, let's say I have an array items = "P1", "P3", null, null
- P4 appears (items =
"P1", "P3", "P4", null
) - P4 doesn't exist yet, so I just add it to the smallest index
null
. - But then P1 reappears, so point P1 goes to
null
(items =null, "P3", "P4", null
) - I need a way ( my question ) to offset everything like this (items =
"P3", "P4", null, null
) - Then add P1 to the lowest index
null
(items ="P3", "P4", "P1", null
) - And so on, LRU tracking
So I need to find a way to move all non-null elements to the beginning of the array (in order).
I found a post that used this items = items.Where(s => !String.IsNullOrEmpty(s)).ToArray();
one however this removes all null
s when I want to keep the array size intact.
How can I keep the size of the array by moving all zeros to the end and all nonzeros to the front (keeping all values ββin order)
source to share
Here is a solution that doesn't create a new array. It just rebuilds the existing array.
static void MoveFront<T>(T[] arr) where T : class
{
int ileft = 0;
int iright = 1;
while (iright < arr.Length)
{
T left = arr[ileft];
T right = arr[iright];
if (left == null && right != null)
{
Swap(arr, ileft++, iright++);
}
else if (left == null && right == null)
{
iright++;
}
else if (left != null && right != null)
{
ileft += 2;
iright += 2;
}
else if (left != null && right == null)
{
ileft++;
iright++;
}
}
}
static void Swap<T>(T[] arr, int left, int right)
{
T temp = arr[left];
arr[left] = arr[right];
arr[right] = temp;
}
Name it like this:
string[] arr = { "a", null, "b", null, "c" };
MoveFront(arr);
source to share