-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathInsertionSort.cs
More file actions
67 lines (63 loc) · 2.49 KB
/
InsertionSort.cs
File metadata and controls
67 lines (63 loc) · 2.49 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
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 InsertionSort
{
public static void Sort(int[] nums, PictureBox graph, List<Bars> bars)
{
//passes through each index
for (int i = 1; i < nums.Length; i++)
{
int temp = nums[i]; //value will be overridden, so temp store
SortPage.Reads++;
SortPage.UpdateReadLbl();
int pointer = i; //position where current value will be inserted
//checks values are in range and in order
SortPage.Comparisons++;
SortPage.UpdateComparisonLbl();
for (; pointer > 0 && temp < nums[pointer - 1]; pointer--)
{
nums[pointer] = nums[pointer - 1]; //copies value to the right index
SortPage.Comparisons++;
SortPage.UpdateComparisonLbl();
SortPage.Writes++;
SortPage.UpdateWriteLbl();
SortPage.Reads+=2;
SortPage.UpdateReadLbl();
AddSwapBar(pointer, bars);
UpdateGraph(SortPage.Delay, graph, bars);
}
nums[pointer] = temp; //reinserts value, replacing duplicate
SortPage.Writes++;
SortPage.UpdateWriteLbl();
AddSwapBar(pointer, bars);
UpdateGraph(SortPage.Delay, graph, bars);
}
UpdateGraph(0, graph, bars);
}
private static void AddSwapBar(int i, List<Bars> bars)
{
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, PictureBox graph, List<Bars> bars)
{
//updates panel
for (int j = 0; j < bars.Count; j++)
{
graph.Invalidate(bars[j].Region);
}
graph.Update();
Thread.Sleep(delay);
}
}
}