[C#] Bubble Sort

  • 1393
  • 0

摘要:[C#] Bubble Sort

氣泡排序是最簡單直覺的演算法

時間複雜度為O(NxN)

因為交換次數過多所以用C#跑起來是最慢的

 

        public static void n2_BubbleSort(int[] array, bool descend)
        {
            int end = array.Length - 1;
            int begin = 0;
            while (end > 0)
            {
                for (int i = begin; i < end; i++)
                {
                    if ((!descend && array[i] > array[i + 1]) || (descend && array[i + 1] > array[i]))
                    {
                        swapArray(array, i, i + 1);
                    }
                }
                end--;
            }
        }