常见排序算法:QuickSort

 

 

 

 1 
 2         
 3         public static void Sort(int[] array,int low,int high)
 4         {
 5             // check arguments
 6             int pivotpos = 0;
 7             if(low < high)
 8             {
 9                 pivotpos = Partition(array,low,high);
10                 Sort(array,low,pivotpos);
11                 Sort(array,pivotpos + 1,high);
12             }
13         
14         }        
15         private static int Partition(int[] array,int low,int high)
16         {
17             int tmp = array[low];
18             if(low < high){
19                 // here must be '>=',not only '>'
20                 while (low < high && array[high] >= tmp) {
21                     high--;
22                 }
23                 Swap(ref array[low],ref array[high]);
24                 // here must be '<=',not only '<'
25                 while (low < high && array[low] <= tmp) {                                    
26                     low++;
27                 }                
28                 Swap(ref array[low],ref array[high]);
29             }
30             return low;
31         }
32         private static void Swap(ref int a,ref int b)
33         {
34             int tmp = a;
35             a = b;
36             b = tmp;
37         }

 

 

 ref: http://c.chinaitlab.com/c/basic/200905/785203.html

ref:http://student.zjzk.cn/course_ware/data_structure/web/paixu/paixu8.3.2.1.htm

快速排序(QuickSort)

1、算法思想

     快速排序是C.R.A.Hoare于1962年提出的一种划分交换排序。它采用了一种分治的策略,通常称其为分治法(Divide-and-ConquerMethod)。

(1) 分治法的基本思想
     分治法的基本思想是:将原问题分解为若干个规模更小但结构与原问题相似的子问题。递归地解这些子问题,然后将这些子问题的解组合为原问题的解。

(2)快速排序的基本思想
     设当前待排序的无序区为R[low..high],利用分治法可将快速排序的基本思想描述为:
①分解: 
    
 在R[low..high]中任选一个记录作为基准(Pivot),以此基准将当前无序区划分为左、右两个较小的子区间R[low..pivotpos-1)和R[pivotpos+1..high],并使左边子区间中所有记录的关键字均小于等于基准记录(不妨记为pivot)的关键字pivot.key,右边的子区间中所有记录的关键字均大于等于pivot.key,而基准记录pivot则位于正确的位置(pivotpos)上,它无须参加后续的排序。
  注意:
     划分的关键是要求出基准记录所在的位置pivotpos。划分的结果可以简单地表示为(注意pivot=R[pivotpos]):
     R[low..pivotpos-1].keys≤R[pivotpos].key≤R[pivotpos+1..high].keys
                  其中low≤pivotpos≤high。
②求解: 
     
通过递归调用快速排序对左、右子区间R[low..pivotpos-1]和R[pivotpos+1..high]快速排序。
③组合: 
    
 因为当"求解"步骤中的两个递归调用结束时,其左、右两个子区间已有序。对快速排序而言,"组合"步骤无须做什么,可看作是空操作。

2、快速排序算法QuickSort
  void QuickSort(SeqList R,int low,int high)
   { //对R[low..high]快速排序
     int pivotpos; //划分后的基准记录的位置
     if(low<high){//仅当区间长度大于1时才须排序
        pivotpos=Partition(R,low,high); //对R[low..high]做划分
        QuickSort(R,low,pivotpos-1); //对左区间递归排序
        QuickSort(R,pivotpos+1,high); //对右区间递归排序
      }
    } //QuickSort

  注意:

     为排序整个文件,只须调用QuickSort(R,1,n)即可完成对R[l..n]的排序。 

posted @ 2010-03-25 12:48  Freedom  阅读(244)  评论(0编辑  收藏  举报