快速排序示例代码

  private  void Sort(int[] numbers, int left, int right)
        {
             //左边索引小于右边,则还未排序完成   
               if (left < right)
            {
                //取中间的元素作为比较基准,小于他的往左边移,大于他的往右边移   
                   int middle = numbers[(left + right) / 2];
                int i = left - 1;
                int j = right + 1;
                while (true)
                {
                    while (numbers[++i] < middle && i < right) ;
                    while (numbers[--j] > middle && j > 0) ;
                    if (i >= j)
                        break;
                    Swap(numbers, i, j);

                }        
                Sort(numbers, left, i - 1);
                Sort(numbers, j + 1, right);

                for (int k = 0; k < numbers.Length; k++)
                {
                    Console.WriteLine(numbers[k]);
                }
                Console.ReadLine(); 
            }           
        }

        private  void Swap(int[] numbers, int i, int j)
        {
            int number = numbers[i];
            numbers[i] = numbers[j];
            numbers[j] = number;
        }

 

posted @ 2016-06-05 22:47  斌言  阅读(299)  评论(0编辑  收藏  举报