SoFunction
Updated on 2025-03-06

C# Quick sorting algorithm example implemented using delegate

This article describes the fast sorting algorithm implemented by C# using delegate. Share it for your reference. The details are as follows:

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, -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 = (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); 
 }
} 

I hope this article will be helpful to everyone's C# programming.