Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions QSort/QSort.sln
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@

Microsoft Visual Studio Solution File, Format Version 12.00
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QSort", "QSort\QSort.csproj", "{94307952-BF53-4474-BC48-C9BB49E563F3}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "QSortTest", "QSortTest\QSortTest.csproj", "{1C4FF2C2-4A26-46EE-A1FB-9BC55EA704BE}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Release|Any CPU = Release|Any CPU
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{94307952-BF53-4474-BC48-C9BB49E563F3}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{94307952-BF53-4474-BC48-C9BB49E563F3}.Debug|Any CPU.Build.0 = Debug|Any CPU
{94307952-BF53-4474-BC48-C9BB49E563F3}.Release|Any CPU.ActiveCfg = Release|Any CPU
{94307952-BF53-4474-BC48-C9BB49E563F3}.Release|Any CPU.Build.0 = Release|Any CPU
{1C4FF2C2-4A26-46EE-A1FB-9BC55EA704BE}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{1C4FF2C2-4A26-46EE-A1FB-9BC55EA704BE}.Debug|Any CPU.Build.0 = Debug|Any CPU
{1C4FF2C2-4A26-46EE-A1FB-9BC55EA704BE}.Release|Any CPU.ActiveCfg = Release|Any CPU
{1C4FF2C2-4A26-46EE-A1FB-9BC55EA704BE}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
EndGlobal
65 changes: 65 additions & 0 deletions QSort/QSort/Program.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
using System;
using System.Diagnostics;

namespace QSort
{
class Program
{
static void Main(string[] args)
{
Statistics.CollectStatisticsFromMatrix(1000, 1000);
/*
Результаты на массивах размером 1000.
Количество повторов: 1000.
Паралельная сортировка:
Матожидание = 0,005
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Надо указывать размерность величин

Среднеквадратичное отклонение = 0,1580348062927937
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Среднеквадратичное отклонение на два порядка больше матожидания, это не нормально

Обычная сортировка:
Матожидание = 0,136
Среднеквадратичное отклонение = 0,5399111037939502
#1#

Statistics.CollectStatisticsFromMatrix(1000, 500);
/*
Результаты на массивах размером 1000.
Количество повторов: 500.
Паралельная сортировка:
Матожидание = 0
Среднеквадратичное отклонение = 0
Обычная сортировка:
Матожидание = 0,03
Среднеквадратичное отклонение = 0,1705872210923191
#1#

Statistics.CollectStatisticsFromMatrix(500, 250);
/*
Результаты на массивах размером 500.
Количество повторов: 250.
Паралельная сортировка:
Матожидание = 0
Среднеквадратичное отклонение = 0
Обычная сортировка:
Матожидание = 0
Среднеквадратичное отклонение = 0
#1#
*/

var array = new int[100];
var rand = new Random();
for (int i = 0; i < 100; i++)
{
array[i] = rand.Next(100);
}
var array1 = array;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это не понадобилось, да и в принципе создавать ещё одну ссылку на тот же массив не уверен, что может быть тут полезно

var sorter = new QSort<int>(array);
var timer = new Stopwatch();
timer.Start();
sorter.SortMulti();
timer.Stop();
for (int i = 0; i < array.Length; i++)
{
Console.Write($"{array[i]} ");
}
}
}
}
74 changes: 74 additions & 0 deletions QSort/QSort/QSort.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace QSort
{
public class QSort<T> where T:IComparable
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Нужны комментарии

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
public class QSort<T> where T:IComparable
public class QSort<T> where T: IComparable

{
private IList<T> List;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
private IList<T> List;
private IList<T> list;

camelCase же. Если Вы и HwProj так пишете, мы все обречены :)


public QSort(IList<T> list)
{
this.List = list;
}

private int Partition(int left, int right)
{
int start = right;
int end = left;
while (start != end)
{
if (List[end].CompareTo(List[start]) <= 0)
{
end++;
}
else
{
Swap(end, start);
Swap(end, start - 1);
start--;
}
}
return end;
}

private void Swap(int posOne, int posTwo)
{
(List[posOne], List[posTwo]) = (List[posTwo], List[posOne]);
}

private void SortCall(int start, int end)
{
if (start >= end)
{
return;
}
int partition = Partition(start, end);
SortCall(start, partition - 1);
SortCall(partition + 1, end);
}

public void Sort()
{
SortCall(0, List.Count - 1);
}

private void SortCallMulti(int start, int end)
{
if (start >= end)
{
return;
}
int partition = Partition(start, end);
var task = new Task[2];
task[0] = Task.Run(() => SortCallMulti(start, partition - 1));
task[1] = Task.Run(() => SortCallMulti(partition + 1, end));
Comment on lines +65 to +66
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

А что с ними потом происходит? Их никто не ждёт, их никто не хранит даже. Мы просто тут пожелали, чтобы когда-нибудь эти лямбды отработали, и всё :)

}

public void SortMulti()
{
SortCallMulti(0, List.Count - 1);
}
}
}
12 changes: 12 additions & 0 deletions QSort/QSort/QSort.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Все уже на .NET 6 перешли

<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<DockerDefaultTargetOS>Windows</DockerDefaultTargetOS>
<LangVersion>preview</LangVersion>
</PropertyGroup>

</Project>
75 changes: 75 additions & 0 deletions QSort/QSort/Statistics.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;

namespace QSort
{
public class Statistics
{
public static void CollectStatisticsFromMatrix(int lenght, int count)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Думаю, что это уже не матрица. И lenght пишется как length

{
(var timeParallel, var timeNotParallel) = GetTimeArraySort(count,lenght);
var result = GetStatistics(timeParallel, timeNotParallel);
Console.WriteLine($"Результаты на массивах размером {lenght}.");
Console.WriteLine($"Количество повторов: {count}.");
Console.WriteLine("Паралельная сортировка:");
Console.WriteLine(
$"Матожидание = {result[0].average}\nСреднеквадратичное отклонение = {result[0].standardDeviation}");
Console.WriteLine("Обычная сортировка:");
Console.WriteLine(
$"Матожидание = {result[1].average}\nСреднеквадратичное отклонение = {result[1].standardDeviation}");
}

private static (double average, double standardDeviation)[] GetStatistics(List<long> timeParallel,
List<long> timeNotParallel)
{
var averageParallel = timeParallel.Average();
var averageNotParallel = timeNotParallel.Average();
var dispersionParallel = timeParallel.Select(x => Math.Pow(x - averageParallel, 2)).Average();
var dispersionNotParallel = timeNotParallel.Select(x => Math.Pow(x - averageNotParallel, 2)).Average();
var standardDeviationParallel = Math.Sqrt(dispersionParallel);
var standardDeviationNotParallel = Math.Sqrt(dispersionNotParallel);
var results = new (double, double)[2];
results[0] = (averageParallel, standardDeviationParallel);
results[1] = (averageNotParallel, standardDeviationNotParallel);
return results;
}

private static (List<long>, List<long>) GetTimeArraySort(int count, int lenght)
{
var timeParallel = new List<long>();
var timeNotParallel = new List<long>();
var timer = new Stopwatch();
for (int i = 0; i < count; i++)
{
var array = GenerateArray(lenght);
var sorter = new QSort<int>(array);
timer.Restart();
sorter.SortMulti();
timer.Stop();
timeParallel.Add(timer.ElapsedMilliseconds);
array = GenerateArray(lenght);
sorter = new QSort<int>(array);
timer.Restart();
sorter.Sort();
timer.Stop();
timeNotParallel.Add(timer.ElapsedMilliseconds);
}

return (timeParallel, timeNotParallel);
}

private static int[] GenerateArray(int lenght)
{
var array = new int[lenght];
var random = new Random();
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Создавать тысячу Random-ов может быть плохой идеей по двум причинам:

  • они все делают одно и то же, а память жрут
  • Random инициализируется текущим временем в миллисекундах от начала Эпохи, так что если в одну миллисекунду GenerateArray вызвался дважды, он сгенерит два одинаковых массива

Лучше создать его один раз и передавать сюда.

for (int i = 0; i < lenght; i++)
{
array[i] = random.Next(0, 100);
}

return array;
}
}
}
45 changes: 45 additions & 0 deletions QSort/QSortTest/QSortTest.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
using System;
using NUnit.Framework;
using QSort;

namespace QSortTest
{
public class Tests
{
private int[] _array;

[SetUp]
public void Setup()
{
var array = new int[100];
var rand = new Random();
for (int i = 0; i < 100; i++)
{
array[i] = rand.Next(100);
}
_array = array;
}

[Test]
public void QSortTest()
{
var sorter = new QSort<int>(_array);
sorter.Sort();
for (int i = 0; i < _array.Length - 1; ++i)
{
Assert.IsTrue(_array[i] <= _array[i + 1]);
}
}

[Test]
public void QSortMultiTest()
{
var sorter = new QSort<int>(_array);
sorter.SortMulti();
for (int i = 0; i < _array.Length - 1; ++i)
{
Assert.IsTrue(_array[i] <= _array[i + 1]);
}
}
}
}
21 changes: 21 additions & 0 deletions QSort/QSortTest/QSortTest.csproj
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<Nullable>enable</Nullable>

<IsPackable>false</IsPackable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.11.0" />
<PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.0.0" />
<PackageReference Include="coverlet.collector" Version="3.1.0" />
</ItemGroup>

<ItemGroup>
<ProjectReference Include="..\QSort\QSort.csproj" />
</ItemGroup>

</Project>