[Solved] How to sort (using strand sort algorithm) an array of integers? C# [closed]


Ok, I got bored and wanted to help (also, a question with that quantity of comments cannot be left without an answer :D), so took the Wikipedia PHP implementation and converted it to C#, but after a bit the user added he cannot use generics…

So, I’m posting a full implementation, one with generics and another with it’s own LinkedList, it’s a bit longer but it works (took the Wikipedia example, followed step by step and it behaves exactly as the example table) and it’s also commented so it’s easy to understand (the linked list code is not commented).

And here it comes!

public class StrandSort
{
    public static int[] SortWithGenerics(int[] Values)
    {

        List<int> Original = new List<int>();
        List<int> Result = new List<int>();
        List<int> Sublist = new List<int>();

        Original.AddRange(Values);

        //While we still have numbers to sort
        while (Original.Count > 0)
        {

            //Clear sublist and take first available number from original to the new sublist
            Sublist.Clear();
            Sublist.Add(Original[0]);
            Original.RemoveAt(0);

            //Iterate through original numbers
            for (int x = 0; x < Original.Count; x++)
            {
                //If the number is bigger than the last item in the sublist
                if (Original[x] > Sublist[Sublist.Count - 1])
                {
                    //Add it to the sublist and remove it from original
                    Sublist.Add(Original[x]);
                    Original.RemoveAt(x);
                    //Roll back one position to compensate the removed item
                    x--;

                }

            }

            //If this is the first sublist
            if (Result.Count == 0)
                Result.AddRange(Sublist); //Add all the numbers to the result
            else
            {
                //Iterate through the sublist
                for (int x = 0; x < Sublist.Count; x++)
                {

                    bool inserted = false;

                    //Iterate through the current result
                    for (int y = 0; y < Result.Count; y++)
                    {
                        //Is the sublist number lower than the current item from result?
                        if (Sublist[x] < Result[y])
                        {
                            //Yes, insert it at the current Result position
                            Result.Insert(y, Sublist[x]);
                            inserted = true;
                            break;

                        }

                    }

                    //Did we inserted the item because found it was lower than one of the result's number?
                    if (!inserted)
                        Result.Add(Sublist[x]);//No, we add it to the end of the results

                }

            }

        }

        //Return the results
        return Result.ToArray();
    }

    public static int[] SortWithoutGenerics(int[] Values)
    {

        IntLinkedList Original = new IntLinkedList();
        IntLinkedList Result = new IntLinkedList();
        IntLinkedList Sublist = new IntLinkedList();

        Original.AddRange(Values);

        //While we still have numbers to sort
        while (Original.Count > 0)
        {

            //Clear sublist and take first available number from original to the new sublist
            Sublist.Clear();
            Sublist.Add(Original.FirstItem.Value);
            Original.Remove(Original.FirstItem);

            IntLinkedItem currentOriginalItem = Original.FirstItem;

            //Iterate through original numbers
            while (currentOriginalItem != null)
            {
                //If the number is bigger than the last item in the sublist
                if (currentOriginalItem.Value > Sublist.LastItem.Value)
                {
                    //Add it to the sublist and remove it from original
                    Sublist.Add(currentOriginalItem.Value);
                    //Store the next item
                    IntLinkedItem nextItem = currentOriginalItem.NextItem;
                    //Remove current item from original
                    Original.Remove(currentOriginalItem);
                    //Set next item as current item
                    currentOriginalItem = nextItem;


                }
                else
                    currentOriginalItem = currentOriginalItem.NextItem;

            }

            //If this is the first sublist
            if (Result.Count == 0)
                Result.AddRange(Sublist); //Add all the numbers to the result
            else
            {

                IntLinkedItem currentSublistItem = Sublist.FirstItem;

                //Iterate through the sublist
                while (currentSublistItem != null)
                {

                    bool inserted = false;

                    IntLinkedItem currentResultItem = Result.FirstItem;

                    //Iterate through the current result
                    while (currentResultItem != null)
                    {
                        //Is the sublist number lower than the current item from result?
                        if (currentSublistItem.Value < currentResultItem.Value)
                        {
                            //Yes, insert it at the current Result position
                            Result.InsertBefore(currentResultItem, currentSublistItem.Value);
                            inserted = true;
                            break;

                        }

                        currentResultItem = currentResultItem.NextItem;

                    }

                    //Did we inserted the item because found it was lower than one of the result's number?
                    if (!inserted)
                        Result.Add(currentSublistItem.Value);//No, we add it to the end of the results

                    currentSublistItem = currentSublistItem.NextItem;

                }

            }

        }

        //Return the results
        return Result.ToArray();
    }

    public class IntLinkedList
    {

        public int count = 0;
        IntLinkedItem firstItem = null;
        IntLinkedItem lastItem = null;

        public IntLinkedItem FirstItem { get { return firstItem; } }
        public IntLinkedItem LastItem { get { return lastItem; } }
        public int Count { get { return count; } }

        public void Add(int Value)
        {

            if (firstItem == null)
                firstItem = lastItem = new IntLinkedItem { Value = Value };
            else
            { 

                IntLinkedItem item = new IntLinkedItem{  PreviousItem = lastItem, Value = Value };
                lastItem.NextItem = item;
                lastItem = item;

            }

            count++;

        }

        public void AddRange(int[] Values)
        {

            for (int buc = 0; buc < Values.Length; buc++)
                Add(Values[buc]);

        }

        public void AddRange(IntLinkedList Values)
        {

            IntLinkedItem item = Values.firstItem;

            while (item != null)
            {

                Add(item.Value);
                item = item.NextItem;

            }

        }

        public void Remove(IntLinkedItem Item)
        {
            if (Item == firstItem)
                firstItem = Item.NextItem;

            if (Item == lastItem)
                lastItem = Item.PreviousItem;

            if(Item.PreviousItem != null)
                Item.PreviousItem.NextItem = Item.NextItem;

            if (Item.NextItem != null)
                Item.NextItem.PreviousItem = Item.PreviousItem;

            count--;

        }

        public void InsertBefore(IntLinkedItem Item, int Value)
        {

            IntLinkedItem newItem = new IntLinkedItem { PreviousItem = Item.PreviousItem, NextItem = Item, Value = Value };

            if (Item.PreviousItem != null)
                Item.PreviousItem.NextItem = newItem;

            Item.PreviousItem = newItem;

            if (Item == firstItem)
                firstItem = newItem;

            count++;
        }

        public void Clear()
        {

            count = 0;
            firstItem = lastItem = null;

        }

        public int[] ToArray()
        {

            int[] results = new int[Count];
            int pos = 0;

            IntLinkedItem item = firstItem;

            while (item != null)
            {
                results[pos++] = item.Value;
                item = item.NextItem;
            }

            return results;

        }
    }

    public class IntLinkedItem
    { 

        public int Value;
        internal IntLinkedItem PreviousItem;
        internal IntLinkedItem NextItem;

    }
}

EDIT: It’s really not a linked list but a double linked list 😉

EDIT: Corrected a missing “else” in non-generic implementation

EDIT: I was really bored and created a refactored and corrected version of the user’s code with commented changes so he can learn from it 😉

Note to user: I recommend you to use more meaningful names for variables, it is a lot easier to understand the code when you read it.

    static public int[] SortCorrectedUserCode(int[] Source)
    {
        int[] Sublist,
            Results;
        int ItemsLeft,
            SublistPos,
            ResultPos;//new variable to store current pos in results
        //n; n was useless

        Sublist = new int[Source.Length];
        Results = new int[Source.Length];
        //Avoid resets just using an integer to track array lengths
        //Reset(ref Sublist);
        //Reset(ref Results);
        ItemsLeft = Source.Length;

        ResultPos = 0;

        while (ItemsLeft != 0)
        {
            //n = int.MinValue;
            SublistPos = 0;

            for (int currentSourcePos = 0; currentSourcePos < Source.Length; currentSourcePos++)
            {
                if (Source[currentSourcePos] != int.MaxValue)
                {
                    //Added special treatment for first item in sublist (copy it yes or yes ;D)
                    if (SublistPos == 0 || Source[currentSourcePos] > Sublist[SublistPos])
                    {

                        Sublist[SublistPos] = Source[currentSourcePos];
                        //n = Source[currentSourcePos]; useless
                        Source[currentSourcePos] = int.MaxValue;
                        ItemsLeft--;
                        SublistPos++;
                    }
                }
            }

            //int p3p, zs;

            //pn is never true...
            //bool pn = false;

            //Sublist was being iterated for all it's length, not only for the current items
            //for (int currentSublistPos = 0; currentSublistPos < Sublist.Length; currentSublistPos++)

            for (int currentSublistPos = 0; currentSublistPos < SublistPos; currentSublistPos++)
            {
                //p3p = int.MinValue;

                bool inserted = false;

                //Results was being iterated for all it's length, not only for current items
                //for (int currentResultPos = 0; currentResultPos < Results.Length; currentResultPos++)

                for (int currentResultPos = 0; currentResultPos < ResultPos; currentResultPos++)
                {

                    //This part was never used...
                    //if (pn)
                    //{
                    //    zs = Results[currentResultPos];
                    //    Results[currentResultPos] = p3p;
                    //    p3p = zs;
                    //}
                    //else
                    //{

                    //This IF was wrong, when the code entered this piece of code it started
                    //for subsequent iterations in the current loop to copy data from sublist to list, which is not correct ... I think, not sure 
                    //because it's really confusing
                    //if (Sublist[currentSublistPos] >= p3p && Sublist[currentSublistPos] <= Results[currentResultPos])
                    //{
                    //p3p = Results[currentResultPos];
                    //Results[currentResultPos] = Sublist[currentSublistPos];
                    //}
                    //}

                    //New code, if the item at sublist is lower than the one at results then insert item in current position
                    if (Sublist[currentSublistPos] < Results[currentResultPos])
                    {

                        InsertInArray(currentResultPos, Sublist[currentSublistPos], Results);
                        inserted = true;
                        break;

                    }
                }
                //Did we inserted the item?
                if (!inserted)
                    Results[ResultPos] = Sublist[currentSublistPos]; //If no then just add it to the end of the results

                ResultPos++;
            }

            //Reset(ref Sublist);
        }

        return Results;
    }

    //Helper function to insert a value in an array and displace values to the right
    static void InsertInArray(int Index, int Value, int[] Target)
    {
        //Create temp array of right items
        int[] tempArray = new int[(Target.Length - Index) - 1];

        //Copy items to temp array
        Array.Copy(Target, Index, tempArray, 0, tempArray.Length);

        //Set value at index
        Target[Index] = Value;

        //Copy values from temp array to correct position
        Array.Copy(tempArray, 0, Target, Index + 1, tempArray.Length);

    }

Also did some benchmarking on the functions (because the user was concerned about speed) and those are the results running on my machoine in debug mode (for 5000 items, did not have patience to test longer arrays because old code was very slow):

  • Generics: 36ms
  • Non-generics: 21ms
  • User original code 23248ms
  • Corrected code: 34ms

0

solved How to sort (using strand sort algorithm) an array of integers? C# [closed]