2011年软件设计师辅导:并行排序算法(2)

2011年软件设计师辅导:并行排序算法(2) #
只要实现一个T类型两两比较的接口,然后调用ParallelSort 的 Sort 方法就可以了,是不是很简单?
#
下面是 ParallelSort类的代码 #
using System;
using System.Collections.Generic;
#
using System.Linq;
using System.Text;
using System.Threading; #
namespace Sort
{ #
/**/ ///
#
/// ParallelSort #
///
/// #
public class ParallelSort < T >
{ #
enum Status #
{
Idle = 0 , #
Running = 1 , #
Finish = 2 ,
#
} #
class ParallelEntity #
{ #
public Status Status;
#
public T[] Array; #
public IComparer < T > Comparer; #
public ParallelEntity(Status status, T[] array, IComparer < T > comparer) #
{
#
Status = status; #
Array = array; #
Comparer = comparer;
#
} #
}
private void ThreadProc(Object stateInfo) #
{
#
ParallelEntity pe = stateInfo as ParallelEntity; #
lock (pe)
{ #
pe.Status = ParallelSort < T > .Status.Running; #
Array.Sort(pe.Array, pe.Comparer);
pe.Status = ParallelSort < T > .Status.Finish; #
}
}
#
public void Sort(T[] array, IComparer < T > comparer) #
{ #
// Calculate process count
#
int processorCount = Environment.ProcessorCount;
// If array.Length too short, do not use Parallel sort #
if (processorCount == 1 || array.Length < processorCount) #
{ #
Array.Sort(array, comparer);
return ;
}
#
// Split array #
ParallelEntity[] partArray = new ParallelEntity[processorCount];
#
int remain = array.Length; #
int partLen = array.Length / processorCount;
#