快速排序

1.快速排序

快速排序思想:通过一趟排序将要排序的数据分割成独立的两部分,其中一部分的所有数据都比另外一部分的所有数据都要小,然后再按此方法对这两部分数据分别进行快速排序,整个排序过程可以递归进行,以此达到整个数据变成有序序列

C#代码说明

  /// <summary>
        /// 快速排序
        /// </summary>
        /// <param name="ar">数组</param>
        /// <param name="left">起始位置</param>
        /// <param name="right">结束位置</param>
        /// <returns></returns>
        static int QuickSort(int[] ar,int left,int right) {
            int start, end, point,temp;
            start = left;
            end = right;
           while (start<end)
            {
                point = ar[left];
                while ((start) != end)
                {
                    if (ar[start + 1] <= point)
                    {
                        start++;
                    }
                    else if (ar[end] > point)
                    {
                        end--;
                    }
                    else
                    {

                //在这里分组

                        temp = ar[start + 1];
                        ar[start + 1] = ar[end];
                        ar[end] = temp;
                    }
                }

           //这样小的值就在point前面,大的值就在point后面
                ar[left] = ar[start];
                ar[start] = point;
            }


            foreach (var item in ar)
            {
                Console.Write(item);
                Console.Write(" ");
            }
            Console.WriteLine("");
            return start;
        }

代码说明:简单是实现快速排序调用过程

//初始化数组

var myInt = new[] { 5, 41, 4,89,9,3,2,1 };

//定义三个变量分别存放:第一趟排序分组中间值的位置,第2趟排序分组中间值的位置,第3趟排序分组中间值的位置

   int temp,t1,t2;
   temp=QuickSort(myInt,0,myInt.Length-1);
         t1 = temp;
         t2 = temp;

//这里用While循环,循环结束后,返回值必定是临时变量t1=1,t2=ar.Length-1,这样因该很明了吧!
         while (t1!=1||t2!=ar.Length-1)
         {
      t1 = QuickSort(myInt, 0, t1 - 1);
      t2 = QuickSort(myInt, t2 + 1, myInt.Length - 1);  
         }

在类中Array.Sort(传入数组),就是快速排序

posted @ 2012-01-07 21:28  刀锋_Master  阅读(247)  评论(0编辑  收藏  举报