分治法排序

 1 /// <summary>
 2 /// 步骤为:
 3 /// 从数列中挑出一个元素,称为 "基准"(pivot),
 4 /// 重新排序数列,所有元素比基准值小的摆放在基准前面,所有元素比基准值大的摆放在基准的后面(相同的数可以到任一边)。在这个分割结束之后,该基准就处于数列的中间位置。这个称为分割(partition)操作。
 5 /// 递归地(recursive)把小于基准值元素的子数列和大于基准值元素的子数列排序。
 6 /// 递归的最底部情形,是数列的大小是零或一,也就是永远都已经被排序好了。虽然一直递归下去,但是这个演算法总会结束,因为在每次的迭代(iteration)中,它至少会把一个元素摆到它最后的位置去。
 7 /// </summary>
 8 using System;
 9 using System.Collections.Generic;
10 using System.Linq;
11 using System.Text;
12 
13 namespace 快速排序    //***对相同元素, 不稳定的排序算法***
14 {
15     //相对来说,快速排序数值越大速度越快 。  快速排序是所有排序里面最快的
16 
17     class Program
18     {
19         static void Main(string[] args)
20         {
21             int[] arr = { 15, 22, 35, 9, 16, 33, 15, 23, 68, 1, 33, 25, 14 }; //待排序数组
22             QuickSort(arr, 0, arr.Length - 1);  //调用快速排序函数。传值(要排序数组,基准值位置,数组长度)
23 
24             //控制台遍历输出
25             Console.WriteLine("排序后的数列:");
26             foreach (int item in arr)
27                 Console.WriteLine(item);
28         }
29 
30         private static void QuickSort(int[] arr, int begin, int end)
31         {
32             if (begin >= end) return;   //两个指针重合就返回,结束调用
33             int pivotIndex = QuickSort_Once(arr, begin, end);  //会得到一个基准值下标
34 
35             QuickSort(arr, begin, pivotIndex - 1);  //对基准的左端进行排序  递归
36             QuickSort(arr, pivotIndex + 1, end);   //对基准的右端进行排序  递归
37         }
38 
39         private static int QuickSort_Once(int[] arr, int begin, int end)
40         {
41             int pivot = arr[begin];   //将首元素作为基准
42             int i = begin;
43             int j = end;
44             while (i < j)
45             {
46                 //从右到左,寻找第一个小于基准pivot的元素
47                 while (arr[j] >= pivot && i < j) j--; //指针向前移
48                 arr[i] = arr[j];  //执行到此,j已指向从右端起第一个小于基准pivot的元素,执行替换
49 
50                 //从左到右,寻找首个大于基准pivot的元素
51                 while (arr[i] <= pivot && i < j) i++; //指针向后移
52                 arr[j] = arr[i];  //执行到此,i已指向从左端起首个大于基准pivot的元素,执行替换
53             }
54 
55             //退出while循环,执行至此,必定是 i= j的情况(最后两个指针会碰头)
56             //i(或j)所指向的既是基准位置,定位该趟的基准并将该基准位置返回
57             arr[i] = pivot;
58             return i;
59         }
60 
61     }
62 }

 

posted @ 2015-09-22 16:13  Czhipu  阅读(179)  评论(0编辑  收藏  举报