-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBubbleSort.cs
More file actions
69 lines (65 loc) · 2.4 KB
/
BubbleSort.cs
File metadata and controls
69 lines (65 loc) · 2.4 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
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 BubbleSort
{
public static void Sort(int[] nums, PictureBox graph, List<Bars> bars)
{
//Reads = Writes = Comparisons = 0;
bool swapped = true; //checks if swapped in last pass
for (int passes = 0; passes < nums.Length && swapped == true; passes++)
{
swapped = false;
for (int i = 0; i < nums.Length - 1 - passes; i++)
{
SortPage.Reads+=2;
SortPage.UpdateReadLbl();
SortPage.Comparisons++;
SortPage.UpdateComparisonLbl();
if (nums[i] > nums[i + 1])
{
Swap(nums, i, i + 1); //swaps value if in wrong order
swapped = true; //swapped, so true
//adds bars that were swapped
AddSwapBar(i, bars);
AddSwapBar(i + 1, bars);
//uses bars to update graph
UpdateGraph(bars, graph, SortPage.Delay);
UpdateGraph(bars, graph, 0);
}
}
}
}
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(List<Bars> bars, PictureBox graph, int delay)
{
for (int j = 0; j < bars.Count; j++)
{
graph.Invalidate(bars[j].Region);
}
graph.Update();
Thread.Sleep(delay);
}
private static void Swap(int[] nums, int a, int b)
{
int temp = nums[a];
nums[a] = nums[b];
nums[b] = temp;
SortPage.Writes += 2;
SortPage.UpdateWriteLbl();
}
}
}