forked from aalhour/C-Sharp-Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
/
QuickSorter.cs
72 lines (57 loc) · 2.26 KB
/
QuickSorter.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
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
using System.Collections.Generic;
using Algorithms.Common;
namespace Algorithms.Sorting
{
public static class QuickSorter
{
//
// The public APIs for the quick sort algorithm.
public static void QuickSort<T>(this IList<T> collection, Comparer<T> comparer = null)
{
int startIndex = 0;
int endIndex = collection.Count - 1;
//
// If the comparer is Null, then initialize it using a default typed comparer
comparer = comparer ?? Comparer<T>.Default;
collection.InternalQuickSort(startIndex, endIndex, comparer);
}
//
// Private static method
// The recursive quick sort algorithm
private static void InternalQuickSort<T>(this IList<T> collection, int leftmostIndex, int rightmostIndex, Comparer<T> comparer)
{
//
// Recursive call check
if (leftmostIndex < rightmostIndex)
{
int wallIndex = collection.InternalPartition(leftmostIndex, rightmostIndex, comparer);
collection.InternalQuickSort(leftmostIndex, wallIndex - 1, comparer);
collection.InternalQuickSort(wallIndex + 1, rightmostIndex, comparer);
}
}
//
// Private static method
// The partition function, used in the quick sort algorithm
private static int InternalPartition<T>(this IList<T> collection, int leftmostIndex, int rightmostIndex, Comparer<T> comparer)
{
int wallIndex, pivotIndex;
// Choose the pivot
pivotIndex = rightmostIndex;
T pivotValue = collection[pivotIndex];
// Compare remaining array elements against pivotValue
wallIndex = leftmostIndex;
// Loop until pivot: exclusive!
for (int i = leftmostIndex; i <= (rightmostIndex - 1); i++)
{
// check if collection[i] <= pivotValue
if (comparer.Compare(collection[i], pivotValue) <= 0)
{
collection.Swap(i, wallIndex);
wallIndex++;
}
}
collection.Swap(wallIndex, pivotIndex);
return wallIndex;
}
}
}