iT邦幫忙

0

[C#] Sort an Array 解法

c#
  • 分享至 

  • xImage
  •  

Example 1:

Input: nums = [5,2,3,1]
Output: [1,2,3,5]
Explanation: After sorting the array, the positions of some numbers are not changed (for example, 2 and 3), while the positions of other numbers are changed (for example, 1 and 5).
Example 2:

Input: nums = [5,1,1,2,0,0]
Output: [0,0,1,1,2,5]
Explanation: Note that the values of nums are not necessairly

        static void Main(string[] args)
        {
            QuickSort();
        }

        private static void QuickSort()
        {
            var nums = new int[] { 5, 2, 3, 1};
            QuickSort(nums,0, nums.Length -1);
            Console.WriteLine($"{nums[0]},{nums[1]},{nums[2]},{nums[3]}");
            Console.ReadKey();
        }

        private static void QuickSort(int[] nums, int left, int right)
        {
            if (left >= right) return;
            int partitionIndex = Partition(nums, left, right);
            QuickSort(nums, left, partitionIndex - 1);
            QuickSort(nums, partitionIndex + 1, right);
        }

        private static int Partition(int[] nums, int left, int right)
        {
            int pivot = nums[right];
            int i = left - 1;
            int temp;
            for (int j = left; j < right; j++)
            {
                if (nums[j] < pivot)
                {
                    i++;
                    temp = nums[i];
                    nums[i] = nums[j];
                    nums[j] = temp;
                }
            }

            temp = nums[i+1];
            nums[i + 1] = nums[right];
            nums[right] = temp;
            return i + 1;
        }

快速排序法說明參考


圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言