-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSelectionSort.cs
More file actions
90 lines (83 loc) · 2.85 KB
/
SelectionSort.cs
File metadata and controls
90 lines (83 loc) · 2.85 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
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 SelectionSort
{
private static int[] nums;
private static List<Bars> bars;
private static PictureBox graph;
public static void Sort(int[] numbers, PictureBox box, List<Bars> barsList)
{
nums = numbers;
graph = box;
bars = barsList;
//finds next smallest then moves it infront
for (int i = 0; i < nums.Length - 1; i++)
{
int smallest = FindSmallest(i);
Swap(i, smallest);
AddSwapBar(i);
AddSwapBar(smallest);
UpdateGraph(SortPage.Delay);
}
UpdateGraph(0);
}
private static int FindSmallest(int i)
{
int smallest = i++; //current smallest index
for (; i < nums.Length; i++)
{
AddincrementBar(i);
UpdateGraph(SortPage.Delay);
SortPage.Comparisons++;
SortPage.UpdateComparisonLbl();
SortPage.Reads += 2;
SortPage.UpdateReadLbl();
if (nums[i] < nums[smallest])
{
smallest = i; //assigned as new smallest
}
}
return smallest;
}
private static void Swap(int a, int b)
{
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
SortPage.Writes+=2;
SortPage.UpdateWriteLbl();
}
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 AddincrementBar(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 UpdateGraph(int delay)
{
//updates panel
for (int j = 0; j < bars.Count; j++)
{
graph.Invalidate(bars[j].Region);
}
graph.Update();
Thread.Sleep(delay);
}
}
}