This repository was archived by the owner on Mar 25, 2025. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathProgram.cs
88 lines (69 loc) · 2.1 KB
/
Program.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
namespace _6._Quick_Sort
{
using System;
using System.Linq;
internal class Program
{
static void Main()
{
int[] array = Console.ReadLine().Split(" ", StringSplitOptions.RemoveEmptyEntries).Select(int.Parse).ToArray();
QuickSort<int>(array);
Console.WriteLine(string.Join(" ", array));
}
public static void QuickSort<T>(T[] array) where T : IComparable<T>
{
Shuffle(array);
Sort(array, 0, array.Length - 1);
}
private static void Sort<T>(T[] array, int start, int end) where T : IComparable<T>
{
if (start >= end)
{
return;
}
int p = Partition(array, start, end);
Sort(array, start, p - 1);
Sort(array, p + 1, end);
}
private static void Shuffle<T>(T[] array) where T : IComparable<T>
{
Random random = new Random();
for (int i = 0; i < array.Length; i++)
{
int rnd = i + random.Next(0, array.Length - i);
Swap(array, i, rnd);
}
}
private static int Partition<T>(T[] array, int start, int end) where T : IComparable<T>
{
if (start >= end)
{
return start;
}
int low = start;
int high = end + 1;
while (true)
{
while (array[++low].CompareTo(array[start]) < 0)
{
if (low == end) break;
}
while (array[start].CompareTo(array[--high]) < 0)
{
if (high == start) break;
}
if (low >= high)
{
break;
}
Swap(array, low, high);
}
Swap(array, start, high);
return high;
}
static void Swap<T>(T[] array, int low, int high)
{
(array[high], array[low]) = (array[low], array[high]);
}
}
}