Skip to main content

Insertion Sort


The implementation of insertion sort is very well known, but to improve upon the standard description this method uses System.Collections.ObjectModel.IComparable, allowing it to sort a range of types, and the class and methods are marked as static.  Both modifications make the methods more reusable than in typical examples.

            IComparable[] start = new IComparable[] {44, 2,4,1,6,7,33,25,5,2};
            IComparable[] result = InsertionSort.Sort(start);

            IComparable[] startAlpha = new IComparable[] { "r", "A", "z", "c", "a", "h"};
            IComparable[] resultAlpha = InsertionSort.Sort(startAlpha);

The two lower routines are useful for quick sort, in that they will handle portions of arrays

Class

static class InsertionSort
    {
        /// <summary>
        /// Given a list of items, sorts by
        /// 1. examining each item from first position
        /// 2. calls method to insert value at correct sorted position
        /// </summary>
        /// <param name="startingList"></param>
        /// <returns></returns>
        public static IComparable[] Sort(IComparable[] startingList)
        {
            int arrayLength = startingList.Length;
            for (int counter = 0; counter < arrayLength; counter++)
            {
                startingList = Insert(startingList, counter);
            }
            return startingList;
        }

        /// <summary>
        /// 1. moves each value that is larger than current item's value back one
        /// 2. finaly inserting value at the correct position
        /// </summary>
        /// <param name="list"></param>
        /// <param name="position"></param>
        /// <returns></returns>
        private static IComparable[] Insert(IComparable[] list, int position)
        {
            int counter = position - 1;
            IComparable value = list[position];
            while (counter >= 0 && (list[counter].CompareTo(value) > 0))
            {
                list[counter + 1] = list[counter];
                counter = counter - 1;
            }
            list[counter + 1] = value;
            return list;
        }

        /// <summary>

        /// Given a list of items, sorts by
        /// 1. examining each item from starting index to endIndex, not necessarily the end of arry
        ///    - starting/ending indexes alllow this to be used with quick sort and portions of arrays
        /// 2. calls method to insert value at correct sorted position
        /// </summary>
        /// <param name="startingList"></param>
        /// <param name="startIndex"></param>
        /// <param name="endIndex"></param>
        /// <returns></returns>
        public static int[] Sort(int[] startingList, int startIndex, int endIndex)
        {
            for (int counter = startIndex; counter <= endIndex; counter++)
            {
                startingList = Insert(startingList, counter);
            }
            return startingList;
        }

        /// <summary>
        /// 1. moves each value that is larger than current item's value back one
        /// 2. finaly inserting value at correct position for value
        /// </summary>
        /// <param name="list"></param>
        /// <param name="position"></param>
        /// <returns></returns>
        private static int[] Insert(int[] list, int position)
        {
            int counter = position-1;
            int value = list[position];
            while (counter >= 0 && (list[counter].CompareTo(value) > 0))
            {
                list[counter + 1] = list[counter];
                counter = counter - 1;
            }
            list[counter + 1] = value;
            return list;
        }
    }

Comments

Popular posts from this blog

Review - TFS/VSTS - Great Product, Ideal for Small Development Shops

This is a report a short review I provided for G2 regarding TFS : What do you like best? If you use Visual Studio for development, TFS, or its online equivalent VSTS, you can have a fairly seamless end-to-end integration. Out of the box, it provides code management, testing, work hierarchy in agile formats, automated build, and deployment. What do you dislike? Branching and merging can be a bit painful, in that it needs to be planned, and is not natively part of the process. Code review also needs to be planned and only recently has it become part of the process. Recommendations to others considering the product My only concern regarding TFS and VSTS is that Microsoft itself recommends using Git. What business problems are you solving with the product? What benefits have you realized? In my current role, I've joined a shop that has application development as secondary to their role of desktop OS and app deployment/maintenance, so their code management practi...

Complexity: A Guided Tour

Complexity: A Guided Tour by Melanie Mitchell My rating: 4 of 5 stars I enjoy reading in systems and complexity, and this was a nice addition to my shelf, with a slightly different take than other books. I found a few areas in the first half a bit tedious, overly long, repetitive, and not illuminating, but generally, it's a great overview of seminal work and very thought-provoking. The first half overlaps but nicely differs from other books I've read, covering things like chaos and information processing, and the latter half of the book I found more engaging, focused on models, computation, network science, and scaling. As mentioned, although I found the first half a bit of a slog at times, the second half was very engaging. View all my reviews

Do Algorithms Make You a Better Developer?

Responding to a question on HashNode, Developers who practise algorithms are better at software development than people who just do development. Is it true? , I wrote the following: My feeling is that algorithms help make one a better programmer, but that is likely true of many coding concepts. I did not have algorithms as an undergraduate, so my knowledge is acquired through reading and practice, but after reading and applying Algorithm's in a Nutshell, I felt the quality of my work improved. That said, my development work increased more after understanding Design Patterns, or after consuming books on database design.  Since many types of knowledge improve developing and architecting abilities, one has to consider how it helps and to what degree. Algorithms are coding-in-the-small, often narrowly focused solutions, but which can have a great impact at scale. For many applications, a focus on algorithms would be overkill as data sets and requirements do not require it. In this ...