Algorithmic-Insert Sorting Demo

Insert Sort

Sorting principle:
1. Divide all elements into two groups, sorted and unsorted
2. Find the first element in the unsorted group and insert it into the sorted group
3. Recurse through the sorted elements and compare them with the elements to be inserted. Find an element that is less than or equal to the element to be inserted. Place the element to be inserted in this position, and move the other elements one place back.

Source code

/// <summary>
    ///insert sort
    /// </summary>
    public class InsertSort
    {
        public static List<int[]> result = new List<int[]>();

        public static void sort(int[] a)
        {
            result.Clear();
            result.Add((int[])a.Clone());
            for (int i = 1; i < a.Length; i++)
            {
                for (int j = i; j > 0; j--)
                {
                    if (compareTo(a[j-1], a[j]))
                    {
                        exec(a,j-1,j);
                        result.Add((int[])a.Clone());
                    }
                    else
                        break;
                }
            }
        }

        /// <summary>
        ///swap elements in two locations
        /// </summary>
        /// <param name="a"></param>
        /// <param name="i"></param>
        /// <param name="j"></param>
        private static void exec(int[] a, int i, int j)
        {
            int temp = a[j];
            a[j] = a[i];
            a[i] = temp;
        }

        /// <summary>
        ///Determine the size of two elements
        /// </summary>
        /// <param name="i"></param>
        /// <param name="j"></param>
        /// <returns></returns>
        private static bool compareTo(int i, int j)
        {
            return i > j;
        }
    }

Demonstration


Time Complexity
The number of comparisons is (N-1)+ (N-2)+...+2+1=N^2/2-N/2
The number of exchanges is (N-1)+(N-2)+...+2+1=N^2/2-N/2
The total number of executions is N^2-N
That is, O(N^2)

Tags: less

Posted on Mon, 08 Jun 2020 14:01:20 -0400 by woozy