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;
第一考试网友情提示:如果您遇到任何疑问,请登录第一考试网考试辅导频道或添加qq:,第一考试网以“为考友服务”为宗旨,秉承“快乐学习,轻松考试!”的理念,旨在为广大考友打造一个良好、温馨的学习与交流平台,欢迎持续关注。以上是小编为大家推荐的《2011年软件设计师辅导:并行排序算法(2)》相关信息。
编辑推荐