环球网校是美国纳斯达克上市企业欢聚时代(NASDAQ:YY)旗下品牌 | 住房和城乡建设部 建筑人才培训合作单位
您现在的位置在: > 计算机类 > 软件水平认证考试 > 考试辅导 >

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

2011-03-15 来源:互联网 作者:第一考试网

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;

#

责编: 返回顶部  打印

关于我们联系我们友情链接网站声明网站地图广告服务帮助中心