Search code examples
algorithmsortinglanguage-agnosticarray-algorithms

Sort an large array, keeping some elements in place (every language)


Can everybody help me? I have a problem: Given an array of array elements (Unlimited number of array elements). Sort the elements in ascending order, but keep any elements with the value -1 in the original position.

example: a=[4, -1, 5, 1, 8, 3, 2, -1]

after sort: a=[1, -1, 2, 3, 4, 5, 8, -1]


Solution

  • Here's how you might accomplish that in C#:

    using System;
    using System.Collections.Generic;
    
    namespace NameSpace
    {
        class Class
        {
            static int[] a = { 4, -1, 5, 1, 8, 3, 2, -1 };
            static List<int> Storage = new List<int>();
            static int indexToAdd = 0;
            static void Main()
            {
                foreach(int i in a)
                {
                    if(i != -1)
                    {
                        Storage.Add(i);
                    }
                }
                Storage.Sort();
    
                for(int i = 0; i < Storage.Count; i++)
                {
                    if(a[indexToAdd + i] == -1)
                    {
                        indexToAdd++;
                    }
                    a[indexToAdd + i] = Storage[i];
                }
    
                foreach(int i in a)
                {
                    Console.WriteLine(i);
                }
                Console.Read();
            }
        }
    }