-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cs
More file actions
50 lines (42 loc) · 1.34 KB
/
Copy pathQuickSort.cs
File metadata and controls
50 lines (42 loc) · 1.34 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
using CommonStuff;
using System;
using System.Diagnostics;
using System.Linq;
namespace Algorithms
{
public static class QuickSort
{
public static void Sort(int[] array, int left, int right)
{
if (left < right && left>= 0 && right >= 0)
{
int pivot = Partition(array, left, right);
if (pivot != -1)
{
Sort(array, left, pivot - 1);
Sort(array, pivot + 1, right);
}
}
}
static int Partition(int[] array, int left, int right)
{
if (left > right) return -1;
//swap pivot with last element
int valuePivot = array[right]; // choose last one to pivot, easy to code
// move all elements less than pivot value before
var newPivot = left;
for (int i = left; i < right; i++)
{
if (array[i] < valuePivot)
{
// swap values greater with smaller than pivot
array.Swap(newPivot, i);
newPivot++;
}
}
// swap first element greater than pivot
array.Swap(newPivot, right);
return newPivot;
}
}
}