C#简单实现泛型数组QSort
原创文章,未经允许,请勿转载
Talk is cheap,show me the code
public class UIPanel
{
public int depth;
}
public class Test
{
/***************快速排序功能****************/
public delegate int QSortCompareFunction<T>(T a,T b);
public static void QSort<T>(T[] array,QSortCompareFunction<T> compareFunc)
{
//排序算法: 插入排序
for(int i = 1; i < array.Length; i++)
{
T t = array[i];
int j = i;
while( (j>0) && compareFunc(array[j-1] , t) > 0 )
{
array[j] = array[j-1];
--j;
}
array[j] = t;
}
}
/************快速排序功能结束***************/
static int UIPanelSortBy(UIPanel a,UIPanel b)
{
if(a.depth > b.depth)return 1;
if(a.depth < b.depth)return -1;
return 0;
}
static void PrintArray(UIPanel[] panels)
{
System.Console.Write("[");
for(int i = 0; i < panels.Length; i++)
{
if(i != 0)System.Console.Write(",");
System.Console.Write(panels[i].depth);
}
System.Console.Write("]\n");
}
static void Main(string[]args)
{
UIPanel[] panels = {
new UIPanel(){depth = 6},new UIPanel(){depth = 2},new UIPanel(){depth = 1}
,new UIPanel(){depth = 4},new UIPanel(){depth = 5},new UIPanel(){depth = 3}
,new UIPanel(){depth = 2},new UIPanel(){depth = 5},new UIPanel(){depth = 7}
};
PrintArray(panels);
QSort<UIPanel>(panels,UIPanelSortBy);
PrintArray(panels);
}
}
来源:悠游悠游,原文地址:https://yymmss.com/p/c-sharp-qsort.html