Performs insertion sort on the list. - CSharp System.Collections.Generic

CSharp examples for System.Collections.Generic:List

Description

Performs insertion sort on the list.

Demo Code


using System.Collections.Generic;

public class Main{
        /// <summary>
        /// Performs insertion sort on the list.
        /// </summary>
        /// <typeparam name="T">List element type</typeparam>
        /// <param name="i_List">The list.</param>
        /// <param name="i_Comparer">The comparer.</param>
        public static void InsertionSort<T>(this IList<T> i_List, IComparer<T> i_Comparer = null)
        {// ww  w . ja  v  a  2 s  . com
            IComparer<T> comparer = i_Comparer ?? Comparer<T>.Default;
            int size = i_List.Count;
            for (int index = 1; index < size; ++index)
            {
                int readIndex = index - 1;
                T examinedValue = i_List[index];
                //early break test for quicker processing of almost sorted arrays
                bool requireSort = comparer.Compare(i_List[readIndex], examinedValue) > 0;
                if (requireSort)
                {
                    while (requireSort)
                    {
                        i_List[readIndex + 1] = i_List[readIndex];
                        requireSort = (readIndex > 0) && comparer.Compare(i_List[--readIndex], examinedValue) > 0;
                    }
                    i_List[readIndex] = examinedValue;
                }
            }
        }
        /// <summary>
        /// Performs insertion sort on the array.
        /// </summary>
        /// <typeparam name="T">Array element type.</typeparam>
        /// <param name="i_Array">The array.</param>
        /// <param name="i_Comparer">An optional comparer.</param>
        public static void InsertionSort<T>(this T[] i_Array, IComparer<T> i_Comparer = null)
        {
            IComparer<T> comparer = i_Comparer ?? Comparer<T>.Default;
            int size = i_Array.Length;
            for (int index = 1; index < size; ++index)
            {
                int readIndex = index - 1;
                T examinedValue = i_Array[index];
                //early break test for quicker processing of almost sorted arrays
                if (comparer.Compare(i_Array[readIndex], examinedValue) > 0)
                {
                    while ((readIndex >= 0) && (comparer.Compare(i_Array[readIndex], examinedValue) > 0))
                    {
                        i_Array[readIndex + 1] = i_Array[readIndex];
                        --readIndex;
                    }
                    i_Array[readIndex + 1] = examinedValue;
                }
            }
        }
}

Related Tutorials