欢迎光临
我们一直在努力

【算法】C#快速排序类-.NET教程,C#语言

建站超值云服务器,限时71元/月

快速排序的基本思想是基于分治策略的。对于输入的子序列ap..ar,如果规模足够小则直接进行排序,否则分三步处理:

分解(divide):将输入的序列ap..ar划分成两个非空子序列ap..aq和aq+1..ar,使ap..aq中任一元素的值不大于aq+1..ar中任一元素的值。

递归求解(conquer):通过递归对p..aq和aq+1..ar进行排序。

合并(merge):由于对分解出的两个子序列的排序是就地进行的,所以在ap..aq和aq+1..ar都排好序后不需要执行任何计算ap..ar就已排好序。

这个解决流程是符合分治法的基本步骤的。因此,快速排序法是分治法的经典应用实例之一。

using system;

namespace vcquicksort

{

/// <summary>

/// classquicksort 快速排序。

/// 范维肖

/// </summary>

public class quicksort

{

public quicksort()

{

}

private void swap(ref int i,ref int j)

//swap two integer

{

int t;

t=i;

i=j;

j=t;

}

public void sort(int [] list,int low,int high)

{

if(high<=low)

{

//only one element in array list

//so it do not need sort

return;

}

else if (high==low+1)

{

//means two elements in array list

//so we just compare them

if(list[low]>list[high])

{

//exchange them

swap(ref list[low],ref list[high]);

return;

}

}

//more than 3 elements in the arrary list

//begin quicksort

myquicksort(list,low,high);

}

public void myquicksort(int [] list,int low,int high)

{

if(low<high)

{

int pivot=partition(list,low,high);

myquicksort(list,low,pivot-1);

myquicksort(list,pivot+1,high);

}

}

private int partition(int [] list,int low,int high)

{

//get the pivot of the arrary list

int pivot;

pivot=list[low];

while(low<high)

{

while(low<high && list[high]>=pivot)

{

high–;

}

if(low!=high)

{

swap(ref list[low],ref list[high]);

low++;

}

while(low<high && list[low]<=pivot)

{

low++;

}

if(low!=high)

{

swap(ref list[low],ref list[high]);

high–;

}

}

return low;

}

}

}

赞(0)
版权申明:本站文章部分自网络,如有侵权,请联系:west999com@outlook.com 特别注意:本站所有转载文章言论不代表本站观点! 本站所提供的图片等素材,版权归原作者所有,如需使用,请与原作者联系。未经允许不得转载:IDC资讯中心 » 【算法】C#快速排序类-.NET教程,C#语言
分享到: 更多 (0)