-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cs
More file actions
102 lines (95 loc) · 3.61 KB
/
QuickSort.cs
File metadata and controls
102 lines (95 loc) · 3.61 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace SortingVisualiser
{
class QuickSort
{
private static int[] nums;
private static PictureBox graph;
private static List<Bars> bars;
public static void Sort(int[] numbers, PictureBox box, List<Bars> barsList)
{
//copies numbers to nums
graph = box;
nums = numbers;
bars = barsList;
//split is entire array length
Split(0, nums.Length - 1);
}
public static void Split(int start, int end)
{
if (start < end)
{ //condition to end recurtion
int lastpivot = Pivot(start, end); //return final position of pivot
AddPivotBar(lastpivot);
UpdateGraph(0);
Split(start, lastpivot - 1); //repeats Pivoting on left
Split(lastpivot + 1, end); //repeats Pivoting on right
}
}
public static int Pivot(int start, int end)
{
SortPage.Reads++;
SortPage.UpdateReadLbl();
int PivotValue = nums[end]; //gets value of pivot
int lastswap = start; //index to swap when smaller than pivot
for (int i = start; i < end; i++)
{
SortPage.Reads++;
SortPage.UpdateReadLbl();
SortPage.Comparisons++;
SortPage.UpdateComparisonLbl();
if (nums[i] < PivotValue)
{ //if less than pivot
Swap(i, lastswap); //swaps with pointer
lastswap++; //left of lastswap is less than pivot
}
}
Swap(lastswap, end); //moves pivot into the correct place
return lastswap;
}
private static void Swap(int a, int b)
{
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
SortPage.Writes += 2;
SortPage.UpdateWriteLbl();
AddSwapBar(a);
AddSwapBar(b);
UpdateGraph(SortPage.Delay);
UpdateGraph(0);
}
private static void AddSwapBar(int i)
{
RectangleF rectangle = new RectangleF(new PointF(i * SortPage.WidthConstant, 0),
new SizeF(SortPage.WidthConstant, 9999));
Bars bar = new Bars(SortPage.CreateRectangle(i), new Region(rectangle));
bars.Add(bar);
}
private static void AddPivotBar(int i)
{
RectangleF rectangle = new RectangleF(new PointF(i * SortPage.WidthConstant, 0),
new SizeF(SortPage.WidthConstant, 9999));
Bars bar = new Bars(SortPage.CreateRectangle(i),
Color.FromArgb(255, 153, 255, 51) ,new Region(rectangle));
bars.Add(bar);
}
private static void UpdateGraph(int delay)
{
//updates panel
for (int j = 0; j < bars.Count; j++)
{
graph.Invalidate(bars[j].Region);
}
graph.Update();
Thread.Sleep(delay);
}
}
}