[C#] Selection Sort

  • 2352
  • 0

摘要:[C#] Selection Sort

選擇排序演算法選出最大或最小值

時間複雜度也是O(NxN)

交換次數比Bubble Sort 少

所以用C#跑起來略快於Bubble

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