-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortingAlgorithms.cs
More file actions
36 lines (34 loc) · 1.12 KB
/
SortingAlgorithms.cs
File metadata and controls
36 lines (34 loc) · 1.12 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
using System;
using System.Collections.Generic;
namespace SortingVisualization
{
public static class SortingAlgorithms
{
/**
* Bubble Sort. Can sort all types that are comparable.
* Returns list of all swaps that took place chronologically
*/
public static List<(int, int)> BubbleSort<T>(T[] values) where T : IComparable
{
List<(int, int)> steps = new List<(int, int)>();
var itemMoved = false;
do
{
itemMoved = false;
for (int i = 0; i < values.Length - 1; i++)
{
if (values[i].CompareTo(values[i + 1]) > 0)
{
var lowerValue = values[i + 1];
values[i + 1] = values[i];
values[i] = lowerValue;
// Record which pair of indexes were swapped
steps.Add((i, i + 1));
itemMoved = true;
}
}
} while (itemMoved);
return steps;
}
}
}