13,190
社区成员
发帖
与我相关
我的任务
分享
public static void Sort<T>(List<T> arrayForSort, int startIndex, int endIndex, Func<T, T, bool> CompareMethod)
{
if (startIndex >= endIndex)
{
return;
}
int pointer = startIndex;
int end = endIndex;
for (int i = pointer + 1; i <= end; i++)
{
if (CompareMethod(arrayForSort[pointer], arrayForSort[i]))//把比当前锚点数小的数全部移到锚点数左边
{
var temp = arrayForSort[pointer];
arrayForSort[pointer] = arrayForSort[i];
arrayForSort[i] = temp;
pointer = i;
}
else//若当前比较的数比锚点数大 则将其与最后面的数对调
{
var temp = arrayForSort[end];
arrayForSort[end] = arrayForSort[i];
arrayForSort[i] = temp;
--i;
--end;
}
}
Sort<T>(arrayForSort, startIndex, pointer, CompareMethod);
Sort<T>(arrayForSort, pointer + 1, endIndex, CompareMethod);
}
public static void SortUsingTask<T>(List<T> arrayForSort, int startIndex, int endIndex, Func<T, T, bool> CompareMethod)
{
if (startIndex >= endIndex)
{
return;
}
int pointer = startIndex;
int end = endIndex;
for (int i = pointer + 1; i <= end; i++)
{
if (CompareMethod(arrayForSort[pointer], arrayForSort[i]))//把比当前锚点数小的数全部移到锚点数左边
{
var temp = arrayForSort[pointer];
arrayForSort[pointer] = arrayForSort[i];
arrayForSort[i] = temp;
pointer = i;
}
else//若当前比较的数比锚点数大 则将其与最后面的数对调
{
var temp = arrayForSort[end];
arrayForSort[end] = arrayForSort[i];
arrayForSort[i] = temp;
--i;
--end;
}
}
new Task(() => SortUsingTask<T>(arrayForSort, startIndex, pointer, CompareMethod)).Start();
new Task(() => SortUsingTask<T>(arrayForSort, pointer + 1, endIndex, CompareMethod)).Start();
}
class Program
{
static void Main(string[] args)
{
Random rdm = new Random();
List<int> testList = new List<int>();
List<int> testList2 = new List<int>();
List<int> testList3 = new List<int>();
for (int i = 0; i < 100000; i++)
{
var number = rdm.Next(1000000);
testList.Insert(i, number);
testList2.Insert(i, number);
testList3.Insert(i, number);
}
var watch1 = new Stopwatch();
watch1.Start();
QuickSortMain.Sort<int>(testList, 0, testList.Count-1, (x, y) => { return x > y; });
watch1.Stop();
var customSort = watch1.ElapsedMilliseconds;
watch1.Reset();
watch1.Start();
QuickSortMain.SortUsingTask<int>(testList2, 0, testList2.Count - 1, (x, y) => { return x > y; });
watch1.Stop();
var customSort2 = watch1.ElapsedMilliseconds;
watch1.Reset();
watch1.Start();
testList3.Sort();
watch1.Stop();
var systemSort = watch1.ElapsedMilliseconds;
Console.WriteLine("无并行计算版本 Custom1 Sort:" + customSort);//快排,比较方法用了lambda,容器为list<int>
Console.WriteLine("并行计算版本 Custom2 Sort:" + customSort2);//快排,比较方法用了lambda,容器为list<int>
Console.WriteLine("C#自带排序方法 System Sort:" + systemSort);//系统自带排序
Console.ReadLine();
}
}