[C#] Sort an Array 解法

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;        }

快速排序法说明参考


关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章