-
Notifications
You must be signed in to change notification settings - Fork 294
/
Copy pathBubbleSort.cs
36 lines (31 loc) · 963 Bytes
/
BubbleSort.cs
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 Advanced.Algorithms.Sorting;
/// <summary>
/// A bubble sort implementation.
/// </summary>
public class BubbleSort<T> where T : IComparable
{
/// <summary>
/// Time complexity: O(n^2).
/// </summary>
public static T[] Sort(T[] array, SortDirection sortDirection = SortDirection.Ascending)
{
var comparer = new CustomComparer<T>(sortDirection, Comparer<T>.Default);
var swapped = true;
while (swapped)
{
swapped = false;
for (var i = 0; i < array.Length - 1; i++)
//compare adjacent elements
if (comparer.Compare(array[i], array[i + 1]) > 0)
{
var temp = array[i];
array[i] = array[i + 1];
array[i + 1] = temp;
swapped = true;
}
}
return array;
}
}