-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuickSort.cs
More file actions
79 lines (72 loc) · 1.66 KB
/
QuickSort.cs
File metadata and controls
79 lines (72 loc) · 1.66 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
68
69
70
71
72
73
74
75
76
77
78
79
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
/*
* Quick Sort : Quick sort is Divide and Conquer aalgorithem.
* It picks an element as pivot and partitions the given array around the piked pivot.
*
* Always pick first element as pivot.
* Always pick last element as Pivot.
* Pick a random element as pivot.
* Pick median as pivot.
*/
namespace ConsoleApp169
{
internal static class Program
{
public static void Main()
{
int[] arr = new int[] { 2, 5, -4, 11, 0, 18, 22, 67, 51, 6 };
foreach (var variable in arr)
{
Console.Write(variable +" , ");
}
Quick_Sort(arr, 0, arr.Length - 1);
foreach (var variable in arr)
{
Console.Write(variable + " , ");
}
}
private static void Quick_Sort(int[] arr, int i, int arrLength)
{
if (i < arrLength )
{
int pivot = Partition(arr, i, arrLength);
if (pivot > 1)
{
Quick_Sort(arr,i,pivot-1);
}
if (pivot+1 < arrLength )
{
Quick_Sort(arr,pivot+1,arrLength);
}
}
}
private static int Partition(int[] arr, int i, int arrLength)
{
int pivot = arr[i];
while (true)
{
while (arr[i] < pivot)
{
i++;
}
while (arr[arrLength] > pivot)
{
arrLength--;
}
if (i < arrLength)
{
if (arr[i] == arr[arrLength]) return arrLength;
int temp = arr[i];
arr[i] = arr[arrLength];
arr[arrLength] = temp;
}
else
{
return arrLength;
}
}
}
}
}