C#快速排序

//快速排序的具体过程如下:

//1:在待排序的n个记录中,任取一个作为基准,把数组分为两部分,第一组的排序码都小于或等于该排序码,第二组的排序码,都大于或等于该排序码,并把该基准放在两组中间。

 2:采用同样的方法分别对左右两组进行排序,直到所有的记录都排到适当的位置。

///快速递归排序

        private static void QuickSort(int[] R, int low, int high)

        {

            int pivotLoc = 0;

            if (low < high)

            {

                pivotLoc = Partition(R, low, high);

                QuickSort(R, low, pivotLoc - 1);

                QuickSort(R, pivotLoc + 1, high);

            }

        }

        private static int Partition(int[] R, int low, int high)

        {

            int temp = R[low];

            while (low < high)

            {

                if (low < high && temp <= R[high])

                {

                    high--;

                }

                R[low] = R[high];

                if (low < high && R[low] <= temp)

                {

                    low++;

                }

                R[high] = R[low];

            }

            R[low] = temp;

            return low;

 

        }

 

        //快速非递归排序

        public static void QuickSort(int [] R,int Low,int High,Stack<int> stack)

        {

            int low = Low;

            int high = High;

            int temp = R[low];

            while (high > low)

            {

                while (low < high && temp <= R[high])

                {

                    high--;

                }

                if (high > low)

                {

                    R[low] = R[high];

                    R[high] = temp;

                }

                while (low < high && temp >= R[low])

                {

                    low++;

                }

                if (high > low)

                {

                    R[high] = R[low];

                    R[low] = temp;

                }

                if (Low < low - 1)

                {

                    stack.Push(Low);

                    stack.Push(low-1);

                }

                if (High > low + 1)

                {

                    stack.Push(low+1);

                    stack.Push(High);

                }

            }

        }

发布了23 篇原创文章 · 获赞 0 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章