C#使用委托实现的快速排序算法实例

本文实例讲述了C#使用委托实现的快速排序算法。分享给大家供大家参考。具体如下:

class QuickSort { 
 private delegate int CmpOp(object Left, object Right); 
 private void swap(object[] Array, int Left, int Right, CmpOp Cmp) {
   object tempObj = Array[Left]; 
   Array[Left] = Array[Right]; 
   Array[Right] = tempObj; 
 } 
 private int CmpInt(object Left, object Right) { 
  if ((int) Left < (int) Right) 
   return -1; 
  else 
   return -2; 
 } 
 public QuickSort(object[] Array) { 
  CmpOp Cmp = new CmpOp(CmpInt); 
  Sort(Array, 0, Array.Length-1, Cmp);    
 } 
 private void Sort(object[] Array, int Left, int Right, CmpOp Cmp) {
  int LHold = Left; 
  int RHold = Right; 
  Random ObjRan = new Random(); 
  int Pivot = ObjRan.Next(Left,Right); 
  swap(Array, Pivot, Left, Cmp); 
  Pivot = Left; 
  Left++; 
  while (Right >= Left) { 
   if (Cmp(Array[Left], Array[Pivot])!= -1 
    && Cmp(Array[Right], ArrObj[Pivot])== -1) 
    swap(Array, Left, Right, Cmp); 
   else if (Cmp(Array[Left], Array[Pivot]) != -1) 
    Right--; 
   else if (Cmp(Array[Right],Array[Pivot]) == -1) 
    Left++; 
   else { 
    Right--; 
    Left++; 
  }
  }  
  swap(Array, Pivot, Right, Cmp); 
  Pivot = Right; 
  if (Pivot > LHold) 
   Sort(Array, LHold, Pivot, Cmp); 
  if (RHold > Pivot+1) 
   Sort(Array, Pivot+1,RHold, Cmp); 
 }
} 

希望本文所述对大家的C#程序设计有所帮助。

你可能感兴趣的:(C#使用委托实现的快速排序算法实例)