[C#] Insertion Sort

  • 2211
  • 0
  • 2012-04-16

摘要:[C#] Insertion Sort

插入排序演算法觀念簡單

但是用程式碼表示會變得很複雜

時間複雜度是O(NxN)

實際跑起來總迴圈數(時間複雜度)比Bubble和Selection少一些

用C#跑起來比Selection好,大約是Bubble的兩倍速

但是與O(NlogN)比較起來是不同等級的東西

速度排名 Insertion > Selection > Bubble

        public static void n2_InsertionSort(int[] array, bool descend)
        {           
            int end = array.Length - 1;
            int begin = 1;
            while (begin <= end)
            {
                int temp = array[begin];
                int forward = begin;                
                while(forward > 0 && ((!descend && array[forward-1] > temp) || (descend && array[forward-1] < temp)))
                {
                    array[forward] = array[--forward];
                }
                array[forward] = temp;
                begin++;
            }
        }