-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSorting.cs
More file actions
67 lines (59 loc) · 2.1 KB
/
QuickSorting.cs
File metadata and controls
67 lines (59 loc) · 2.1 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;
namespace DA.Algorithms.Sorting
{
public static class QuickSorting
{
/// <summary>
/// Quicksort is a recursive algorithm that each step selects a pivot
/// and then partition the array into the smallest parts.
/// <para>Time Complexity - O(n log n)</para>
/// </summary>
/// <param name="array">a collection with an elements</param>
public static void Sort<T> (T[] array) where T : IComparable<T>
{
QuickSort (array, 0, array.Length - 1);
}
/// <summary>
/// Quicksort is a recursive algorithm that each step selects a pivot
/// and then partition the array into the smallest parts.
/// <para>Time Complexity - O(n log n)</para>
/// </summary>
/// <typeparam name="T">type of an array</typeparam>
/// <param name="array">a collection with an elements</param>
private static void QuickSort<T> (T[] array, int lower, int upper) where T : IComparable<T>
{
if (upper <= lower) return;
T pivot = array[lower];
int startIndex = lower;
int stopIndex = upper;
while (lower < upper)
{
while (array[lower].CompareTo (pivot) <= 0 && lower < upper)
{
++lower;
}
while (array[upper].CompareTo (pivot) > 0 && lower <= upper)
{
--upper;
}
if (lower < upper)
{
Swap (array, lower, upper);
}
}
Swap (array, upper, startIndex);
QuickSort (array, startIndex, upper - 1);
QuickSort (array, upper + 1, stopIndex);
}
/// <summary>
/// Swap two elements of an array.
/// </summary>
private static void Swap<T> (T[] array, int first, int second)
{
T temp = array[first];
array[first] = array[second];
array[second] = temp;
}
}
}