快速排序

using System;

namespace Recursion
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = { 9,8, 7 ,6, 5, 4, 3, 2, 1 };
            int[] a1 = { 1,2, 6, 5,  4, 3 };

            QuickSort(a1, 0, a1.Length-1);
            Console.WriteLine(string.Join(",", a1));
    } 
} 

/// <summary>
        /// 快速排序获取分区点
        /// </summary>
        public static int Partition(int[]array,int left,int right) 
        {
            
            var pivot = right;
            var cursor = left;
            while (left<=right)
            {
                if (array[left] <= array[ pivot]) 
                {
                  var temp=  array[cursor];
                    array[cursor] = array[left];
                    array[left] = temp;
                    left++;//比对数据位置
                    cursor++;//存放数据位置
                }
                else
                {
                    left++;
                }

            }
            return cursor-1;//当前对枢轴
        }

        private static void QuickSort(int[] arr, int left, int right)
        {
            if (left < right)
            {
                int i = Partition(arr, left, right);
                //if (i <=0 || i > arr.Length - 1) return;
                
                //对枢轴的左边部分进行排序
                QuickSort(arr, left, i-1);
                //对枢轴的右边部分进行排序
                QuickSort(arr, i+1, right);
            }
        }              

 

posted on 2022-01-26 20:02  跨界农民工  阅读(22)  评论(0编辑  收藏  举报

导航