-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathQuick Sort.cpp
More file actions
105 lines (94 loc) · 1.37 KB
/
Quick Sort.cpp
File metadata and controls
105 lines (94 loc) · 1.37 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
/*
Quick Sort
Time Complexity: O(N*logN)
*/
#include <iostream>
using namespace std;
void swap(int A[], int i, int j)
{
int temp;
temp = A[i];
A[i] = A[j];
A[j] = temp;
}
int find_pivot(int A[], int l, int r)
{
//Pivot is the median of three elements
int a = l;
int b;
if((r-l)%2 == 0)
{
b = (r+l)/2 - 1;
}
else
{
b = (r+l)/2;
}
int c = r-1;
if((A[a]>=A[b] && A[a]<=A[c]) || (A[a]<=A[b] && A[a]>=A[c]))
{
return a;
}
else if((A[a]>=A[b] && A[b]>=A[c]) || (A[a]<=A[b] && A[b]<=A[c]))
{
return b;
}
else
{
return c;
}
//Pivot is the first element of the subarray
/*
return l;
*/
//Pivot is the last elemeny of the subarray
/*
return r-1;
*/
}
int quick_sort(int A[], int l, int r, int p)
{
int i,j;
i = l+1;
j = l+1;
for(j; j<r; j++)
{
if(A[j]<A[p])
{
swap(A, i, j);
i++;
}
}
swap(A, i-1, p);
return i-1;
}
void divide_and_sort(int A[], int l, int r)
{
int pivot = find_pivot(A,l,r);
swap(A, l, pivot);
int next = quick_sort(A, l, r, l);
if(next-1>l)
{
divide_and_sort(A, l, next);
}
if(r-1>next+1)
{
divide_and_sort(A, next+1, r);
}
}
int main()
{
int N;
cin>>N;
int A[N];
for(int i = 0; i<N; i++)
{
cin>>A[i];
}
divide_and_sort(A, 0, N);
for(int i = 0; i<N; i++)
{
cout<<A[i]<<" ";
}
return 0;
}