快速排序

来源:互联网 发布:php判断日期大小 编辑:程序博客网 时间:2024/04/30 18:55
在当前无序区R[1..H]中任取一个数据元素作为比较的"基准"(不妨记为X),用此基准将当前无序区划分为左右两个较小的无序区:R[1..I-1]和R[I+1..H],且左边的无序子区中数据元素均小于等于基准元素,右边的无序子区中数据元素均大于等于基准元素,而基准X则位于最终排序的位置上,即R[1..I-1]≤X.Key≤R[I+1..H](1≤I≤H),当R[1..I-1]和R[I+1..H]均非空时,分别对它们进行上述的划分过程,直至所有无序子区中的数据元素均已排序为止。

  4.2. 排序过程:

  【示例】:

初始关键字 [49 38 65 97 76 13 27 49]

第一次交换后 [27 38 65 97 76 13 49 49]

第二次交换后 [27 38 49 97 76 13 65 49]

第三次交换后 [27 38 13 97 76 49 65 49]

第四次交换后 [27 38 13 49 76 97 65 49]

[27 38 13 49 76 97 65 49]

(一次划分过程)

初始关键字 [49 38 65 97 76 13 27 49]

一趟排序之后 [27 38 13] 49 [76 97 65 49]

二趟排序之后 [13] 27 [38] 49 [49 65]76 [97]

三趟排序之后 13 27 38 49 49 [65]76 97

最后的排序结果 13 27 38 49 49 65 76 97

  各趟排序之后的状态

  4.3. 程序实现

/// <summary>
/// 快速排序法
/// </summary>
/// <param name="dbArray"></param>
/// <param name="StartIndex"></param>
/// <param name="EndIndex"></param>

private static void QuickSort( ref double[] dbArray ,int StartIndex ,int EndIndex)
{
 //基数
 int CurrentIndex = StartIndex ;
 //顺序查找
 bool IsOrderSearched = true ;
 //反序查找
 bool IsDisOrderSearched = true ;
 while(IsOrderSearched || IsDisOrderSearched)
 {
  IsDisOrderSearched = false ;
  IsOrderSearched = false ;
  for(int i =EndIndex ; i>CurrentIndex ;i--)
  {
   if(dbArray[i] < dbArray[CurrentIndex])
   {
    ExChangeValue(ref dbArray[i] ,ref dbArray[CurrentIndex]);
    CurrentIndex = i ;
    IsDisOrderSearched = true ;
    break ;
   }
  }
  for(int i = StartIndex ; i < CurrentIndex ; i++)
  {
   if(dbArray[i] > dbArray[CurrentIndex])
   {
    ExChangeValue(ref dbArray[i] ,ref dbArray[CurrentIndex]);
    CurrentIndex = i ;
    IsOrderSearched = true ;
    break ;
   }
  }
 }
 if( EndIndex - StartIndex > 0 )
 {
  if(CurrentIndex != StartIndex )
  {
   QuickSort(ref dbArray ,StartIndex,CurrentIndex -1);
  }
  if(CurrentIndex != EndIndex)
  {
   QuickSort(ref dbArray ,CurrentIndex+1,EndIndex);
  }
 }
}

/// 交换数据
/// </summary>
/// <param name="A"></param>
/// <param name="B"></param>

private static void ExChangeValue(ref double A , ref double B)
{
 double Temp = A ;
 A = B ;
 B = Temp ;
}  
原创粉丝点击