I\'m looking for a simple implementation of a parallelized (multi-threaded) sort algorithm in C# that can operate on List or Arrays, and possibly using
For the record here is a version without lamda expressions that will compile in C#2 and .Net 2 + Parallel Extensions. This should also work with Mono with its own implementation of Parallel Extensions (from Google Summer of code 2008):
///
/// Parallel quicksort algorithm.
///
public class ParallelSort
{
#region Public Static Methods
///
/// Sequential quicksort.
///
///
///
public static void QuicksortSequential(T [] arr) where T : IComparable
{
QuicksortSequential(arr, 0, arr.Length - 1);
}
///
/// Parallel quicksort
///
///
///
public static void QuicksortParallel(T[] arr) where T : IComparable
{
QuicksortParallel(arr, 0, arr.Length - 1);
}
#endregion
#region Private Static Methods
private static void QuicksortSequential(T[] arr, int left, int right)
where T : IComparable
{
if (right > left)
{
int pivot = Partition(arr, left, right);
QuicksortSequential(arr, left, pivot - 1);
QuicksortSequential(arr, pivot + 1, right);
}
}
private static void QuicksortParallel(T[] arr, int left, int right)
where T : IComparable
{
const int SEQUENTIAL_THRESHOLD = 2048;
if (right > left)
{
if (right - left < SEQUENTIAL_THRESHOLD)
{
QuicksortSequential(arr, left, right);
}
else
{
int pivot = Partition(arr, left, right);
Parallel.Invoke(new Action[] { delegate {QuicksortParallel(arr, left, pivot - 1);},
delegate {QuicksortParallel(arr, pivot + 1, right);}
});
}
}
}
private static void Swap(T[] arr, int i, int j)
{
T tmp = arr[i];
arr[i] = arr[j];
arr[j] = tmp;
}
private static int Partition(T[] arr, int low, int high)
where T : IComparable
{
// Simple partitioning implementation
int pivotPos = (high + low) / 2;
T pivot = arr[pivotPos];
Swap(arr, low, pivotPos);
int left = low;
for (int i = low + 1; i <= high; i++)
{
if (arr[i].CompareTo(pivot) < 0)
{
left++;
Swap(arr, i, left);
}
}
Swap(arr, low, left);
return left;
}
#endregion
}